Reputation: 43
how can I replace the content of the file referenced by fileId with a new content in java.io.File newFileContent. The following function update the content of the file with an empty content
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();
}
Upvotes: 0
Views: 3177
Reputation: 817
The way to update files is changed with v3.
You should not pass the file that was retrieved from google drive as is, rather than you should pass a new file object with your updates only. Example:
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();
Note that, except from it's id, we are not using the 'gDriveFile' object for anything else. In order to update:
You can find more migration guidelines here.
Upvotes: 2
Reputation: 4462
You should use a combination of FileContent class and update() method with three arguments as shown in the example below :
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;
}
}
// ...
}
Upvotes: 0