javagoogle-drive-apigoogle-api-java-client

how to determine number of files in a folder in Grive or list them by date ascending


I'm using the Gdrive Java API and the code I have to list a directory is:

FileList result = driveService.files().list() 
            .setPageSize(100)
            .setFields("nextPageToken, files(id, name, parents)")
            .execute();

However, this assumes there are no more than 100 files in the folder.. how can I list all of them? How can I search a folder for a file? How can I list only the top 100 most recent ones?


Solution

  • If you have more than 100 files, then you can update setPageSize(100) to setPageSize(1000) which is the maximum number of items returned in the list request (didn't find this information in documentation but I tested this and confirmed it allows up to 1000).

    If you have more than 1000 files and want to list all of them then you will need to iterate on the list().execute() and include the nextPageToken in your request, until nextPageToken returns null.

    I guess in your question How can I search a folder for a file? you are referring to how to search for a file in a folder, if this is not the case please clarify. In case you're trying to search for a file in a folder, then you can add a query to your request. (Here is a sample on how to make the request with a query)

    String searchQuery = "name contains 'nameOfFile' and mimeType != 'application/vnd.google-apps.folder' and 'folderID' in parents"
    

    And for your last question, you can add the orderBy parameter in your request and use a valid key like createdTime or modifiedTime.

    orderBy A comma-separated list of sort keys. Valid keys are 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime', 'name', 'name_natural', 'quotaBytesUsed', 'recency', 'sharedWithMeTime', 'starred', and 'viewedByMeTime'. Each key sorts ascending by default, but can be reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedTime desc,name.

    References: