Google Drive API - Check if file exists by file ID

2020-05-01 11:34发布

问题:

I could not find a good way to check if the file exists before downloading it. It seems the API doesnt provide a way to check if the file exists by getting the file by ID.

Basically Im checking if the generated outPutStream size is > 0 to process the file, but I didnt like the solution.

Drive driveService = new Drive.Builder(buildHttpTransport(), JSON_FACTORY, googleCredential).build();

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
  driveService.files().get(this.fileId).executeMediaAndDownloadTo(outputStream);

  if(outputStream.size() == 0)
   processFile()

Ideas are welcome!

回答1:

Well, if you just want to check if the file is existed or not, then you can use the Files: list to list the file on your Google Drive. You can get the id of the file in the results.

If you already know the file id, then you can verify it by using the Files: get.

GET https://www.googleapis.com/drive/v3/files/fileId

You will get a response 200 here if the File id is existed.

For the Java code that you want, check this related SO question if it can help you.