在 Java 中直接从 Google Drive 读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12113343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:38:00  来源:igfitidea点击:

Reading directly from Google Drive in Java

javafile-iogoogle-drive-apigoogle-api-java-client

提问by Sayo Oladeji

Please I need to read the content of a file stored in Google Drive programmatically. I'm looking forward to some sort of
InputStream is = <drive_stuff>.read(fileID);
Any help? I'll also appreciate if I can write back to a file using some sort of

请我需要以编程方式读取存储在 Google Drive 中的文件的内容。我期待着某种
InputStream is = <drive_stuff>.read(fileID);
帮助?如果我可以使用某种方式写回文件,我也会很感激

OutputStream dos = new DriveOutputStream(driveFileID);
dos.write(data);

OutputStream dos = new DriveOutputStream(driveFileID);
dos.write(data);

If this sort of convenient approach is too much for what Drive can offer, please I'll like to have suggestions on how I can read/write to Drive directly from java.io.InputStream / OutputStream / Reader / Writer without creating temporary local file copies of the data I want to ship to drive. Thanks!

如果这种方便的方法对于 Drive 可以提供的东西来说太多了,请我想就如何直接从 java.io.InputStream / OutputStream / Reader / Writer 读取/写入 Drive 而不创建临时本地文件提出建议我要运送到驱动器的数据副本。谢谢!

回答by Alain

Please take a look at the DrEdit Java sample that is available on the Google Drive SDK documentation. This example shows how to authorize and build requests to read metadata, file's data and upload content to Google Drive.

请查看 Google Drive SDK文档中提供的 DrEdit Java 示例。此示例展示了如何授权和构建读取元数据、文件数据和将内容上传到 Google Drive 的请求。

Here is a code snippet showing how to use the ByteArrayContentto upload media to Google Drive stored in a byte array:

这是一个代码片段,展示了如何使用ByteArrayContent将媒体上传到存储在字节数组中的 Google Drive:

/**
 * Create a new file given a JSON representation, and return the JSON
 * representation of the created file.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
  Drive service = getDriveService(req, resp);
  ClientFile clientFile = new ClientFile(req.getReader());
  File file = clientFile.toFile();

  if (!clientFile.content.equals("")) {
    file = service.files().insert(file,
        ByteArrayContent.fromString(clientFile.mimeType, clientFile.content))
        .execute();
  } else {
    file = service.files().insert(file).execute();
  }

  resp.setContentType(JSON_MIMETYPE);
  resp.getWriter().print(new Gson().toJson(file.getId()).toString());
}

回答by pinoyyid

Here's a (incomplete) snippet from my app which might help.

这是我的应用程序中的一个(不完整)片段,可能会有所帮助。

            URL url = new URL(urlParam);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection
                .setRequestProperty("Authorization",
                        "OAuth "+accessToken);

        String docText = convertStreamToString(connection.getInputStream());

回答by jpllosa

Using google-api-services-drive-v3-rev24-java-1.22.0:

To read the contents of a file, make sure you set DriveScopes.DRIVE_READONLYwhen you do GoogleAuthorizationCodeFlow.Builder(...)in your credential authorizing method/code.

You'll need the fileIdof the file you want to read. You can do something like this:
FileList result = driveService.files().list().execute();
You can then iterate the resultfor the fileand fileIdyou want to read.

使用 google-api-services-drive-v3-rev24-java-1.22.0:

要读取文件的内容,请确保在凭据授权方法/代码中设置DriveScopes.DRIVE_READONLY执行GoogleAuthorizationCodeFlow.Builder(...)时间。

您将需要fileId要阅读的文件的 。你可以做这样的事情:
FileList result = driveService.files().list().execute();
然后你可以迭代resultforfile并且fileId你想要阅读。

Once you have done that, reading the contents would be something like this:

一旦你这样做了,阅读内容将是这样的:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId).executeMediaAndDownloadTo(outputStream);
InputStream in = new ByteArrayInputStream(outputStream.toByteArray());

回答by V.Barod

// Build a new authorized API client service. Drive service = getDriveService();

// 构建一个新的授权 API 客户端服务。驱动服务 = getDriveService();

    // Print the names and IDs for up to 10 files.
    FileList result = service.files().list()
         .setPageSize(10)
         .setFields("nextPageToken, files(id, name)")
         .execute();

    List<File> files = result.getFiles();
    if (files == null || files.size() == 0) {
        System.out.println("No files found.");
    } else {
        System.out.println("Files:");
        for (File file : files) {
            System.out.printf("%s (%s)\n", file.getName(), file.getId());
            String fileId = file.getId();

                Export s=service.files().export(fileId, "text/plain");
                InputStream in=s.executeMediaAsInputStream();
                InputStreamReader isr=new InputStreamReader(in);
                BufferedReader br = new BufferedReader(isr);
                String line = null;

                StringBuilder responseData = new StringBuilder();
                while((line = br.readLine()) != null) {
                    responseData.append(line);
                }
                System.out.println(responseData);
            } 
        }
    }