简体   繁体   English

使用Java的Google云端硬盘文件下载失败

[英]File download failed for Google Drive using java

I am trying to download all the files available on my Google Drive account, But the file which is getting downloaded, contains only a part of the text written as compared to the original file. 我正在尝试下载Google云端硬盘帐户上的所有可用文件,但是与原始文件相比,正在下载的文件仅包含部分文字内容。 I have made my code work by reading different post's from Google Drive and Stackoverflow posts, so may be am doing something wrong which I am unable to spot out.I am making an desktop application. 我通过阅读Google云端硬盘和Stackoverflow帖子中的不同帖子来使代码正常工作,所以可能是做错了我无法发现的错误。我正在制作桌面应用程序。 Here's the code I have implemented. 这是我实现的代码。

  public class CMDApp {

     private static String CLIENT_ID = "CLIENT_ID";
     private static String CLIENT_SECRET = "Client_Secret";

     private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
     //  private static String REDIRECT_URI = "http://localhost/authCode";
     public static void main(String[] args) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,    Arrays.asList(DriveScopes.DRIVE))
        .setAccessType("online")
        .setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    //System.out.println("Please open the following URL in your browser then type the authorization code:");
    JOptionPane.showMessageDialog(null,"After you click \"OK\" button,\n You will be taken to Google Drive webpage on your deafault browser,\n where you will be asked for permission to give access to application.\nClick \"Accept\" on GDrive webpage(you might have to log in first)");
    Desktop.getDesktop().browse(java.net.URI.create(url));
    String code = JOptionPane.showInputDialog(null, "Copy paste the code displayed on the webpage into this window");
    //System.out.println("  " + url);

//    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//    String code = br.readLine();

    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    //Create a new authorized API client
    Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();

    List<File> result = new ArrayList<File>();
    result=retrieveAllFiles(service);


    for(File f:result){         
        String ext = null;
        System.out.println("File Name==>"+f.getTitle());
        System.out.println("File Id==>"+f.getId());
        System.out.println("File ext==>"+f.getFileExtension());
        System.out.println("File size==>"+f.getFileSize());
        InputStream in = downloadFile(service,f);
        String fileType = f.getMimeType();
        if(fileType.equals("text/plain"))
        {
            ext = ".txt";
        }
        byte b[] = new byte[in.available()];
        in.read(b);
        java.io.File ff = new java.io.File("C:\\GDrive_Download\\"+f.getTitle()+ ext);
        FileOutputStream fout = new FileOutputStream(ff);
        fout.write(b);
        fout.close();
} 
    //Insert a file  
//    File body = new File();
//    body.setTitle("RealtekLog");
//    body.setDescription("A test document");
//    body.setMimeType("text/plain");
//    
//   
////    downloadFile(service, body);
//    
//    java.io.File fileContent = new java.io.File("C:\\GDrive_Download\\My document.txt");
//    FileContent mediaContent = new FileContent("text/plain", fileContent);
//
//    File file = service.files().insert(body, mediaContent).execute();
//    System.out.println("File ID: " + file.getId());
    System.exit(0);
  }

  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;
        }
      }
  private static List<File> retrieveAllFiles(Drive service) throws IOException {
        List<File> result = new ArrayList<File>();
        Files.List request = service.files().list();

        do {
          try {
            FileList files = request.execute();

            result.addAll(files.getItems());
            request.setPageToken(files.getNextPageToken());
          } catch (IOException e) {
            System.out.println("An error occurred: " + e);
            request.setPageToken(null);
          }
        } while (request.getPageToken() != null &&
                 request.getPageToken().length() > 0);

        return result;
      }
      // ...
}

I also has the upload code which works smoothly. 我也有上传代码,可以正常工作。 But download is troubling me. 但是下载令我困扰。 All the experts out their need your help. 所有专家都需要您的帮助。 The txt file present on GDrive has following data GDrive上存在的txt文件具有以下数据

Hello world! this is the test for download done on GDrive , for the code written in java which will do the work of syncing the file to the cloud.

Hello world! 你好,世界! this is the test for download done on GDrive , for the code written in java which will do the work of syncing the file to the cloud. 这是在GDrive上进行的下载测试,适用于用Java编写的代码,该代码可以完成将文件同步到云的工作。

Hello world! 你好,世界! this is the test for download done on GDrive , for the code written in java which will do the work of syncing the file to the cloud. 这是在GDrive上进行的下载测试,适用于用Java编写的代码,该代码可以完成将文件同步到云的工作。

Hello world! 你好,世界! this is the test for download done on GDrive , for the code written in java which will do the work of syncing the file to the cloud. 这是在GDrive上进行的下载测试,适用于用Java编写的代码,该代码可以完成将文件同步到云的工作。

And file which is getting downloaded is having following data 并且正在下载的文件具有以下数据

Hello world! this is the test

Thanks in advance & Merry Christmas. 在此先感谢您和圣诞快乐。

Use this Code 使用此代码

    String filename = "C:\\folder name where you save file\\filename";
response.setContentType("application/octet-stream");
String disHeader = "Attachment; Filename=\"filename\"";
response.setHeader("Content-Disposition", disHeader);
File fileToDownload = new File(filename);

InputStream in = null;
ServletOutputStream outs = response.getOutputStream();

try {
in = new BufferedInputStream
(new FileInputStream(fileToDownload));
int ch;
while ((ch = in.read()) != -1) {
outs.print((char) ch);
}
}
finally {
if (in != null) in.close(); // very important
}

outs.flush();
outs.close();
in.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM