Home » Java » Using Google Drive API with Java, how to list only files in the Drive Section/Folder

Using Google Drive API with Java, how to list only files in the Drive Section/Folder

Posted by: admin December 28, 2021 Leave a comment

Questions:

I am trying to get all files that are in a specific section of Google Drive (The Drive Section).

Those are the files I am looking for:

enter image description here

You can see a folder named Projet 3 and a file named Processus TP2 questions. In the folder I only have one file.

But when I try to list all the files, I get thousands of files. If I search for them using the search bar on top of Google Drive, it finds them, but I have no idea where they are (maybe Gmail attachement?).

This is my search query:

FileList result = service.files().list()
    
    .setQ("mimeType != 'application/vnd.google-apps.folder' 
            and trashed = false")
    
    .setSpaces("drive")
    .setFields("nextPageToken, files(id, name, parents)")
    .setPageToken(pageToken)
    
    .execute();

How can I list only the files I can see in my Drive Section/Folder on the web UI?

Thank you very much.

Answers:

Use “parents” property in your query, like this:

FileList result = service.files().list()
    
.setQ("'root' in parents and mimeType != 'application/vnd.google-apps.folder' and trashed = false")
    
.setSpaces("drive")
.setFields("nextPageToken, files(id, name, parents)")
.setPageToken(pageToken)
    
.execute();

If you want to list the contents of a specific folder rather than root – use that folder’s id instead of ‘root’ in the query.

###

You may actually retrieve a list of your files by sending HTTP request with all the applicable parameters given in Files: list.

This sample code is given in the documentation:

private static List<File> retrieveAllFiles(Drive service) throws IOException {
    List<File> result = new ArrayList<File>();
    Files.List request = service.files().list();

    do {
      try {
        FileList files = request.execute();

        result.addAll(files.getItems());
        request.setPageToken(files.getNextPageToken());
      } catch (IOException e) {
        System.out.println("An error occurred: " + e);
        request.setPageToken(null);
      }
    } while (request.getPageToken() != null &&
             request.getPageToken().length() > 0);

    return result;
  }

Aside from that, you might need to consider using available scopes like requesting full drive scope since you have the need related to listing or reorganizing files in user’s Drive as discussed in Choose Auth Scopes.

Request format:

(https://www.googleapis.com/auth/drive)