10

My Application works with Google Drive Java API.

I want to create folder in the root of the Google Drive only if it does not exist. I am using below code to creat folder.

  file = service.files().insert(body).execute();

How do i check the folder existance in the root folder. I have only the folder name 'Myapp', not the instance ID.

Mohammed H
  • 6,880
  • 16
  • 81
  • 127
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153

2 Answers2

13
Files.List request = service.files().list().setQ(
       "mimeType='application/vnd.google-apps.folder' and trashed=false");
FileList files = request.execute();

You could now go through all folders in "files" and check if any of the folders have the searched title.

Don't forget to loop through all pages with:

request.setPageToken(files.getNextPageToken());

Edit:

Maybe you could have a look at this site. You can add the title in your search criteria instead so you do not have to retrieve all the folders.

iixi
  • 570
  • 1
  • 6
  • 21
  • 7
    That will work, but I think a query of "mimeType='application/vnd.google-apps.folder' and trashed=false and title='MyApp' and 'root' in parents " will either return the folder he's looking for, or an empty list so no need to iterate through nextPageToken – pinoyyid Oct 10 '12 at 11:36
  • @pinoyyid Exactly. That is what I meant in the edit of my first answer. – iixi Oct 10 '12 at 12:08
  • Correction: as of today, to query for a file or directory name, the field is `name` and not `title` as suggested above. – salezica Nov 10 '20 at 14:15
3
Files.List request=service().files().list().setQ(
                   "mimeType='application/vnd.google-apps.folder' and trashed=false and name='"+folderName+"'");
        FileList files = request.execute();

Above line of code is used to get the list of all the files/folder with given name. If files are empty, it means files or the folder with given name doesn't exist and you can create a new folder with below mentioned line of code:

File fileMetadata = new File();
        fileMetadata.setName(folderName);
        fileMetadata.setMimeType("application/vnd.google-apps.folder");

        File file = service().files().create(fileMetadata)
            .setFields("id")
            .execute();
Deepak Jha
  • 81
  • 5