使用Google Drive API V3更新文件

时间:2016-10-02 18:17:07

标签: java google-drive-api

如何使用 java.io.File newFileContent 中的新内容替换 fileId 引用的文件内容。以下函数使用空内容

更新文件的内容
public static void updateDriveFile(Drive service, java.io.File newFileContent, String fileId) {

    com.google.api.services.drive.model.File emptyContent = new File();
    emptyContent.setTrashed(true);
    service.files().update(fileId, emptyContent).execute();
}

2 个答案:

答案 0 :(得分:0)

您应该将FileContent类和update()方法与三个参数结合使用,如下面的example所示:

import com.google.api.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

import java.io.IOException;
// ...

public class MyClass {

  // ...

  /**
   * Update an existing file's metadata and content.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to update.
   * @param newTitle New title for the file.
   * @param newDescription New description for the file.
   * @param newMimeType New MIME type for the file.
   * @param newFilename Filename of the new content to upload.
   * @param newRevision Whether or not to create a new revision for this
   *        file.
   * @return Updated file metadata if successful, {@code null} otherwise.
   */
  private static File updateFile(Drive service, String fileId, String newTitle,
      String newDescription, String newMimeType, String newFilename, boolean newRevision) {
    try {
      // First retrieve the file from the API.
      File file = service.files().get(fileId).execute();

      // File's new metadata.
      file.setTitle(newTitle);
      file.setDescription(newDescription);
      file.setMimeType(newMimeType);

      // File's new content.
      java.io.File fileContent = new java.io.File(newFilename);
      FileContent mediaContent = new FileContent(newMimeType, fileContent);

      // Send the request to the API.
      File updatedFile = service.files().update(fileId, file, mediaContent).execute();

      return updatedFile;
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
      return null;
    }
  }

  // ...
}

答案 1 :(得分:0)

v3更改了文件更新方式。

您不应按原样传递从Google驱动器检索到的文件,而应仅传递包含更新的新文件对象。示例:

File gDriveFile = getAnyFileFromGdrive(.....);

java.io.File fileContent = new java.io.File("<path-of-new-file-on-your-hard-disk>");
FileContent mediaContent = new FileContent("text/plain", fileContent);

File fileObjectWithUpdates = new File();
fileObjectWithUpdates .setDescription("This file was updated");

File updatedFile = drive.files().update(gDriveFile.getId(), fileObjectWithUpdates, mediaContent).execute();

请注意,除了它的ID外,我们没有将'gDriveFile'对象用于其他任何事情。 为了更新:

  • 文件内容->使用“ FileContent”对象
  • 文件描述(或其他任何属性)->使用新的“文件”对象

您可以找到更多migration guidelines here