简体   繁体   中英

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. 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. 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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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