Java调用Google Drive API:如何简便读取深层嵌套目录下的文件?
Great question—traversing each folder level one by one to fetch a file ID is definitely a hassle. Luckily, you can use the Google Drive API's query language to skip the step-by-step calls and locate the file directly in a single request.
Here's how to do it:
1. Use a Nested Query to Match the Full Path
The Drive API lets you write nested select statements in your query to chain together the parent folders in your path (/foo/bar/xpto/some.txt). This way, you can find the target file by verifying its name and all its parent folders in one go.
Here’s a code example:
// Assume you've already set up authenticated Drive service Drive driveService = getAuthenticatedDriveService(); // Build the query to find the file by its full path hierarchy String fileQuery = "name='some.txt' " + "and parents in (select id from files where name='xpto' " + "and parents in (select id from files where name='bar' " + "and parents in (select id from files where name='foo' and parents='root'))) " + "and mimeType!='application/vnd.google-apps.folder'"; // Ensure we get a file, not a folder FileList searchResult = driveService.files().list() .setQ(fileQuery) .setFields("files(id, name)") // Only fetch necessary fields for efficiency .execute(); if (!searchResult.getFiles().isEmpty()) { File targetFile = searchResult.getFiles().get(0); String fileId = targetFile.getId(); // Now read the file content using the ID InputStream fileStream = driveService.files().get(fileId) .executeMediaAsInputStream(); // Process the stream (e.g., read to a string, write to local file) // ... } else { System.err.println("File not found at the specified path!"); }
2. Key Notes for This Approach
- Avoid Duplicate Names: If you have multiple folders/files with the same names in different hierarchies, this query might return multiple results. You can add more filters (like checking folder
mimeTypeexplicitly, or addingtrashed=falseto exclude deleted items) to narrow it down. - Performance: Nested queries are efficient enough for most use cases, but if you're accessing the same paths repeatedly, consider caching the file IDs in a local database or key-value store. This saves you from running the query every time.
- Permissions: Make sure your authenticated service account or user has read access to all folders in the path—otherwise, the query won't find the file.
Alternative: Use Drive's "Path" Metadata (Limited)
Google Drive doesn't natively expose a full file path field, but some third-party libraries or tools might abstract this for you. However, sticking with the official SDK's query language is the most reliable approach without adding extra dependencies.
内容的提问来源于stack exchange,提问作者oleber

