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

标签 java google-drive-api

我正在尝试下载我的 Google 云端硬盘帐户中可用的所有文件,但正在下载的文件与原始文件相比只包含部分文本。我通过阅读来自 Google Drive 和 Stackoverflow 帖子的不同帖子使我的代码工作,所以可能做错了我无法发现的事情。我正在制作桌面应用程序。 这是我实现的代码。

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

我也有运行流畅的上传代码。但是下载让我很困扰。所有的专家都需要你的帮助。 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.

世界,您好!这是在 GDrive 上完成的下载测试,用于用 java 编写的代码,它将完成将文件同步到云的工作。

世界,您好!这是在 GDrive 上完成的下载测试,用于用 java 编写的代码,它将完成将文件同步到云的工作。

世界,您好!这是在 GDrive 上完成的下载测试,用于用 java 编写的代码,它将完成将文件同步到云的工作。

正在下载的文件包含以下数据

Hello world! this is the test

提前致谢,圣诞快乐。

最佳答案

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

关于java - 使用 java 的 Google 云端硬盘文件下载失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20760034/

相关文章:

java - 无法在 Eclipse 中编译 JSP 类。 Apache-Tomcat 9.0.27

java - 从 JPA 2.1 升级到 JPA 2.2

google-apps-script - 合并 Google Docs 文档

google-app-engine - 转换 Appscript 实例以在 Appengine 中运行

javascript - Angular 打印 $scope 函数而不是返回值(当从 DOM 调用时)

node.js - Google 电子表格 - - Node.js

java - 使用 Spring 自注入(inject)

java - 对象相等(对象引用 "==")

java.lang.NoSuchMethodError : No static method clearInstance()

java - 尝试获取 appDataFolder 中的文件列表时出现 GoogleAuthIOException