我正在使用 Java Drive Rest V2 API 开展 Google Drive Integration ,我能够获得除路径之外的大部分文档/文件元数据属性文档/文件。
我也提到了以下StackOverflow问题:
在两个链接中,解决方案表明我必须创建一个单独的方法来实现此要求,这意味着Drive Rest V2 API没有提供直接方法来获取文件路径。
请指导我并就此提出建议。
谢谢,
Arpit
答案 0 :(得分:4)
分享我的解决方案,这对其他人有帮助:))
经过多次谷歌搜索和Google Drive Drive的 Java Drive Rest V2 API ,我知道没有方法可以调用/获取完整的文件路径。
所以我创建了以下两个自定义方法来实现我的问题解决方案:
以下是代码段
public static void main(String[] args) throws IOException {
// Build a new authorized API client service.
Drive service = getDriveService();
try {
// Print the file path and name.
FileList result = service.files().list().execute();
List<File> files = result.getItems();
if (files == null || files.size() == 0) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
if (!(file.getMimeType().contains("folder"))) {
String filePath = null;
if (!(file.getParents().isEmpty())) {
filePath = getFilePath(service, file);
}
System.out.println("path: " + filePath);
System.out.println("name: " + file.getTitle());
System.out.println();
}
}
System.out.println("== END ==");
}
} catch (Exception e) {
System.out.println(e);
}
}
private static String getFilePath(Drive drive, File file) throws IOException {
String folderPath = "";
String fullFilePath = null;
List<ParentReference> parentReferencesList = file.getParents();
List<String> folderList = new ArrayList<String>();
List<String> finalFolderList = getfoldersList(drive, parentReferencesList, folderList);
Collections.reverse(finalFolderList);
for (String folder : finalFolderList) {
folderPath += "/" + folder;
}
fullFilePath = folderPath + "/" + file.getTitle();
return fullFilePath;
}
private static List<String> getfoldersList(Drive drive, List<ParentReference> parentReferencesList, List<String> folderList) throws IOException {
for (int i = 0; i < parentReferencesList.size(); i++) {
String id = parentReferencesList.get(i).getId();
File file = drive.files().get(id).execute();
folderList.add(file.getTitle());
if (!(file.getParents().isEmpty())) {
List<ParentReference> parentReferenceslist2 = file.getParents();
getfoldersList(drive, parentReferenceslist2, folderList);
}
}
return folderList;
}
-
谢谢,
Arpit Bora
答案 1 :(得分:2)
尝试使用Parents.get。成功的请求将返回父级和文件本身的链接。以下是一个示例回复:
{
"kind": "drive#parentReference",
"id": "0Bw-w9jw2bwglbzlvMVh2cll2dmM",
"selfLink": "https://www.googleapis.com/drive/v2/files/1-ABCDEzyvp9NFmWz7h6ssgkTKHytO1Nq4SNIboDW8A/parents/0Bw-w9jw2bwglbzlvMVh2cll2dmM",
"parentLink": "https://www.googleapis.com/drive/v2/files/ABCDEjw2bwglbzlvMVh2cll2dmM",
"isRoot": false
}
以下是文档中的JAVA实现:
private static boolean isFileInFolder(Drive service, String folderId,
String fileId) throws IOException {
try {
service.parents().get(fileId, folderId).execute();
} catch (HttpResponseException e) {
if (e.getStatusCode() == 404) {
return false;
} else {
System.out.println("An error occured: " + e);
throw e;
}
} catch (IOException e) {
System.out.println("An error occured: " + e);
throw e;
}
return true;
}