简体   繁体   中英

Google drive rest API, Download files from root folder only

I am trying to download files in the root directory only. Currently I am not specifying any folders as I do not know how to so it downloads the most recent files that are in other folders that aren't the root. All I would like are the files in the root. The code that is getting the files and the download URLs is below:

public static void startDownload() throws IOException, ParseException {

    Drive serv = getDriveService();

    FileList result = serv.files().list().setMaxResults(10).execute(); //there are 10 files in the root folder     

    List<File> listA = result.getItems();

    if (listA == null || listA.isEmpty()) {
        System.out.println("No files found.");
    } else {
        System.out.println("Files:"+lista.size());
        for (File file : listA) {
            System.out.printf("%s (%s)\n", file.getTitle(), file.getDownloadUrl());
            downloadFile(serv, file);
        }
    }
}

I would like to download all files in the root file only and not in any other folders. Any help would be appreciated.

You need to use the Q parameter to search

q string A query for filtering the file results. See the "Search for Files" guide for supported syntax.

Sending something like the following will return everything that is not a folder with the parent of root.

mimeType != 'application/vnd.google-apps.folder' and 'root' in parents

There are a number of considerations.

Your line 3 needs to be

String q = "trashed = false and 'root' in parents and mimeType != 'application/vnd.google-apps.folder' "

FileList result = serv.files().list().setFields("*").setQ(q).setMaxResults(10).execute();

You need to be aware that this will return a maximum of 10 results, but even more so, you need to be aware that there is no minimum number of results . This means that if you have 11 files, you might get 10 in the first iteration and 1 in the 2nd. However, you could also get 1 and 10, or 3 and 6 and 2, or 0 and 0 and 1 and 10. You need to keep fetching results until the value of getNextPageToken() == null . So your line

if (listA == null || listA.isEmpty()) {

should be something like

if (result.getNextPageToken() == null) {

I realise that you've copy/pasted from the official documentation, but sadly that documentation is wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM