2013-11-27 132 views
2

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

我正在尝试使用Google开发者页面上给出的功能。 (下面的链接)

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

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

我使用下面的功能 -

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; 
    } 
} 

在这里,我没能获得哪些文件应该是该函数的输入参数。 请帮我一把。

回答

0

传一个文件,这里是我做到了。 我并没有下载文件,而是给定文件的所有修订。所以逻辑是一样的。

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(); 
    } 
0

在您的调用方法,设置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/<encrypted_id>"); 
myFile.setId("<encrypted_id>"); 
Drive service = getDriveService(); // Assuming you have a method to authorize and get drive 
BufferedReader br = new BufferedReader(new InputStreamReader(downloadFile(service,myFile)); 
.... 
.... 
... 

注:让你导航到该文件并右键单击该文件的URL,然后选择“获取链接“

相关问题