【问题标题】:How to get text contents of google document via google drive REST api如何通过 google drive REST api 获取 google 文档的文本内容
【发布时间】:2019-05-21 00:46:58
【问题描述】:

我需要从 google 驱动器文档(MIME 类型:application/vnd.google-apps.document)中读取数据,以便将其进一步传递到下游进行处理。

看起来唯一的方法是首先使用files().export(fileId, MIME_TYPE.GoogleDocsDocument.toString()).getMediaHttpDownloader下载文档 , 下载后解析内容,然后使用 files().update 上传包含该文档内容的新文件

我试过用 files().get(fileId).executeMediaAndDownloadTo(outputStream) 但它不允许谷歌文件。我也尝试在他们的文档中挖掘其他方法来做到这一点,但到目前为止还没有运气。

有没有办法避免下载文件?

【问题讨论】:

    标签: java rest google-drive-api


    【解决方案1】:

    我发现我正在尝试将文档导出为 google 文档,这就是我在尝试使用 executeMediaAndDownloadTo 方法时遇到错误的原因。导出为纯文本或其他一些非谷歌格式似乎是必要的。我确信这会导致某种格式问题,但应该可以解决这些问题。这是我最终得到的基本用法。

        public void updateGoogleDocFile(String fileId, String newContent) throws IOException
    {
        try {
            //First retrieve the file from the API as text file
            java.io.File tempDataFile = java.io.File.createTempFile("googleDocsIncomingFile", ".txt");
            OutputStream os = new FileOutputStream(tempDataFile);
            //Convert data to bytes and write to new file
            byte[] fileBytes = downloadGoogleDocFile(fileId).toByteArray();
            os.write(fileBytes);
            //Get new data to append, convert to bytes, and write to file
            byte[] newConentBytes = newContent.getBytes();
            os.write(newConentBytes);
            os.flush();
            os.close();
    
            //File's new metadata.
            File newFile = new File();
            //newFile.setName(fileName);
            //newFile.setDescription("mydescription");
            //newFile.setMimeType(MIME_TYPE.GoogleDocsDocument.toString());
    
            // Send the request to the API.
            FileContent mediaContent = new FileContent(MIME_TYPE.GoogleDocsDocument.toString(), tempDataFile);
            SERVICE.files().update(fileId, newFile, mediaContent).execute();
    
          } catch (IOException e) 
        {
            System.out.println("An error occurred while trying to update the google docs file: " + e);
          }
    }
    
    public ByteArrayOutputStream downloadGoogleDocFile(String fileId) throws IOException
    {
        Export export = SERVICE.files().export(fileId, MIME_TYPE.PlainText.toString());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        export.executeMediaAndDownloadTo(out);
        return out;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      相关资源
      最近更新 更多