Как получить текстовое содержание документа Google через Google REST API - PullRequest
0 голосов
/ 21 мая 2019

Мне нужно прочитать данные из документа на диске Google (MIME-тип: application / vnd.google-apps.document), чтобы я мог передать их дальше для обработки.

Похоже, что единственный способ сделать это - сначала загрузить документ с помощью files().export(fileId, MIME_TYPE.GoogleDocsDocument.toString()).getMediaHttpDownloader, проанализировать содержимое после загрузки, а затем загрузить новый файл с содержимым этого документа с помощью files (). Update

Я пытался использовать files().get(fileId).executeMediaAndDownloadTo(outputStream), но он не разрешает файлы Google.Я также попытался покопаться в их документации, чтобы найти другие способы сделать это, но пока мне не повезло.

Нет ли способа избежать загрузки файла?

1 Ответ

0 голосов
/ 21 мая 2019

Я обнаружил, что пытался экспортировать документ как документ Google, поэтому у меня возникали ошибки при попытке использовать метод executeMediaAndDownloadTo. Экспорт в виде открытого текста или в другом формате, отличном от Google, кажется, необходим для этого. Я уверен, что это вызовет какие-то проблемы с форматированием, но должно быть возможно обойти их. Вот основное использование того, чем я закончил.

    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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...