【问题标题】:How to get Gdoc content from Google Drive API in Java?如何从 Java 中的 Google Drive API 获取 Gdoc 内容?
【发布时间】:2020-12-06 02:48:22
【问题描述】:

我正在尝试使用 Google Drive API 获取 Google 文档的内容。我成功获取了文件夹并获得了 Google Docs 文件 ID。

在API文档上,据说我可以下载这样的文件:

private String getGdoc(String id) throws Exception {
        if(service == null) throw new Exception();
        OutputStream outputStream = new ByteArrayOutputStream();
        service.files().export(id, "text/plain")
            .executeMediaAndDownloadTo(outputStream);
        
        return null;
    }

我的问题是我不想将其写入带有OutputStream 的文件,但我想将文件的内容写入String

所以我尝试使用InputStream

private String getGdoc(String id) throws Exception {
        if(service == null) throw new Exception();
        InputStream inputStream = service.files().export(id, "text/plain")
            .executeMediaAsInputStream();
        
        System.out.println(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
        
        return null;
    }

使用InputStream 我得到了文件的内容,但是我的文档中有一些日文字符并且它们没有显示出来。对于控制台中的这些日文字符,我只得到?。我不知道它来自哪里,因为我指定使用 UTF-8 字符集。

当我尝试使用OutputStream 写入txt 文件时,我没有遇到无法识别字符的问题。

我不知道实现这一目标的最佳方法是什么。你能帮帮我吗?

【问题讨论】:

  • 很有可能您的String 包含正确的数据,并且您打印它的控制台无法显示日文字符(因此将其替换为?)。尝试将String 序列化为其他格式(如 JSON 文件或 XML,使用适当的库),看看是否足够)。
  • 你说得对,这只是控制台的问题。当我在 JTextArea 中显示它时没有问题。

标签: java google-api google-drive-api google-docs-api google-api-java-client


【解决方案1】:

google Drive api 是一个文件存储api。它可以让你上传和下载存储在谷歌驱动器中的文件。下载文件时,您应该将其保存到您的机器上,然后在第三方应用程序中打开它。

如果您想检查和操作存储在 Google 驱动器上的 google 文档文件的内容。您应该考虑使用Google docs api

Google Docs Java quickstart

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.docs.v1.Docs;
import com.google.api.services.docs.v1.DocsScopes;
import com.google.api.services.docs.v1.model.Document;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class DocsQuickstart {
    private static final String APPLICATION_NAME = "Google Docs API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";
    private static final String DOCUMENT_ID = "195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(DocsScopes.DOCUMENTS_READONLY);
    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = DocsQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Docs service = new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        // Prints the title of the requested doc:
        // https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit
        Document response = service.documents().get(DOCUMENT_ID).execute();
        String title = response.getTitle();

        System.out.printf("The title of the doc is: %s\n", title);
    }
}

【讨论】:

  • 可以使用 google drive api。正如第一条评论中所说,这只是控制台的问题。
  • 什么是可能的,什么是预期用途是两个不同的东西。如果您想查看 google doc 文件中的文本,您应该考虑为该用例使用适当的 api。
  • 问题是我在谷歌驱动器中有几个 gdocs。我想获取所有这些,但我不知道如何使用 google docs api 获取文件 ID。
  • 来自 Google drive api 的 filel.ist 会返回给您一个文件 id,然后您可以使用 tine Google Docs api。文件 ID 相同。您将同时使用这两个 API。
  • 好的,谢谢。我没有想到这一点。这无疑是处理这个问题的更好方法。
猜你喜欢
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多