用java从google drive下载pdf和tif文件

用java从google drive下载pdf和tif文件,java,android,pdf,google-api,google-drive-api,Java,Android,Pdf,Google Api,Google Drive Api,我使用下面的代码从谷歌硬盘上下载pdf文件,使用的是GDrive v2 api 当我打开下载的pdf文件时,我收到警告,说文件格式已损坏或不受支持。在google开发者控制台中,他们提到要使用下面的行 String downloadUrl=file.getExportLinks.getapplication/pdf 但是当我使用上面这一行时,我得到了空指针异常。谁能告诉我如何替换代码中的上述行以下载pdf文件并打开该文件。 我还想知道谷歌硬盘上的文件是否已经下载完毕 请帮帮我 提前感谢。您不必在

我使用下面的代码从谷歌硬盘上下载pdf文件,使用的是GDrive v2 api

当我打开下载的pdf文件时,我收到警告,说文件格式已损坏或不受支持。在google开发者控制台中,他们提到要使用下面的行

String downloadUrl=file.getExportLinks.getapplication/pdf

但是当我使用上面这一行时,我得到了空指针异常。谁能告诉我如何替换代码中的上述行以下载pdf文件并打开该文件。 我还想知道谷歌硬盘上的文件是否已经下载完毕

请帮帮我


提前感谢。

您不必在API中选择导出选项,因为pdf文件仅在驱动器中可用,并且没有从Google文档格式转换为任何转换格式(如pdf)。这就是为什么你在获取导出链接时获得NPE。您可以通过直接通过API放置Http Get请求来下载该文件,如下所示

private static InputStream downloadFile(Drive service, File file) { 
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) { 
try { 
HttpResponse resp = 
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())) 
.execute(); 
return resp.getContent(); 
} catch (IOException e) { 
// An error occurred. 
e.printStackTrace(); 
return null; 
} 
} else { 
// The file doesn't have any content stored on Drive. 
return null; 
} 
}
您必须创建一个FileOutputStream,而不是ByteArrayOutputStream,才能使用InputStream创建一个文件。下面的代码片段可能会有所帮助

OutputStream outputStream = new FileOutputStream(new File("/home/input.pdf")); 
int read = 0; 
byte[] bytes = new byte[1024]; 
while ((read = inputStream.read(bytes)) != -1) { 
outputStream.write(bytes, 0, read); 
}
确保在使用后刷新OutputStream并关闭这两个流


注:我在聊天中与OP讨论后得到了这个详细答案。为了简单起见,OP使用TearrayOutputStream而不是FileOutputStream来创建pdf文件。希望这能帮助路过的人

您是否检查了文件id是否正确?如何检查文件id?如何获取文件id?downloadFile方法是如何调用的?String fileID=request.getParameterfileID;System.out.printlnFile ID+fileID;InputStream=null;ServletOutputStream so=null;字节[]bt=null;is=driveaccess.downloadFileserviceGoogleAPI,fileID;是的,我完全理解。如何确认fileID实际上指向Google drive中的正确文件?
OutputStream outputStream = new FileOutputStream(new File("/home/input.pdf")); 
int read = 0; 
byte[] bytes = new byte[1024]; 
while ((read = inputStream.read(bytes)) != -1) { 
outputStream.write(bytes, 0, read); 
}