使用Java API从Google云端硬盘下载文件

我正在使用Java API来创建应用程序。 但是,我无法解决从驱动器下载文件的问题。

我正在尝试使用Google Developer页面上提供的function。 (下方链接)

https://developers.google.com/drive/manage-downloads

但是,没有明确提到如何为特定文件获取/生成downloadURI。 而且我也很困惑如何使用downloadURI下载文件。

我使用以下function –

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) { e.printStackTrace(); return null; } } else { return null; } } 

在这里,我无法获得该文件应该是该函数的输入参数。 请帮帮我。

这是我如何做到的。 我没有下载文档,而是下载给定文档的所有修订版。 所以逻辑是一样的。

  private void downloadRevisions(final RevisionList revisions, final Drive service) { Thread thread = new Thread(new Runnable(){ @Override public void run() { try { //TODO for debugging int i = 0; for (Revision revision : revisions.getItems()) { System.out.println("Thread running: " + i); if (revision.getExportLinks() != null && revision.getExportLinks().get("text/plain") != null && revision.getExportLinks().get("text/plain").length() > 0) { HttpResponse resp = service .getRequestFactory() .buildGetRequest( new GenericUrl(revision .getExportLinks().get("text/plain"))) .execute(); //InputStream inputStream = resp.getContent(); //File Name String revisionFileName = docId+"_"+revision.getId()+"_"+revision.getModifiedDate(); FileOutputStream outputstream = new FileOutputStream(new java.io.File(revisionFileDir, revisionFileName)); IOUtils.copy(resp.getContent(), outputstream,true); outputstream.close(); // writeToFile(inputStream); System.out.println("downloading: " + revisionFileName); } //TODO for debugging i++; } System.out.println("Downloading Done. Document Id: "+docId); } catch (IOException e) { Log.info("WriteToFile Fail", e.toString()); e.printStackTrace(); }finally{ //if( doneFW !=null) // doneFW.close(); } } }); thread.start(); } 

在您的调用方法中,设置fileId和url位置

例如:

 com.google.api.services.drive.model.File myFile = new com.google.api.services.drive.model.File(); myFile.setDownloadUrl("https://drive.google.com/drive/u/0/folders/"); myFile.setId(""); Drive service = getDriveService(); // Assuming you have a method to authorize and get drive BufferedReader br = new BufferedReader(new InputStreamReader(downloadFile(service,myFile)); .... .... ... 

注意:要获取URL,请导航到该文件并右键单击该文件并选择“获取链接”

检查一下

https://developers.google.com/drive/v2/reference/files/list

这将从驱动器返回文件列表,然后您只需要从此列表中传递一个要下载的文件