如何在没有重复的谷歌驱动器中创建文件夹?

问题是:如何在没有重复的情况下在谷歌驱动器中创建文件夹?

我正在回答这篇文章中的问题,我想与正在寻找类似解决方案或问题的任何人分享这些代码。

我遇到的问题是如何在谷歌驱动器中创建文件夹路径,而不会在dirve中结束重复文件夹!

第一个用于从文件标题中检查文件夹存在位置的函数,传递驱动器实例和文件夹的标题,以及它的父项ID(不是标题):

/** * * @param service google drive instance * @param title the title (name) of the folder (the one you search for) * @param parentId the parent Id of this folder (use root) if the folder is in the main directory of google drive * @return google drive file object * @throws IOException */ private File getExistsFolder(Drive service,String title,String parentId) throws IOException { Drive.Files.List request; request = service.files().list(); String query = "mimeType='application/vnd.google-apps.folder' AND trashed=false AND title='" + title + "' AND '" + parentId + "' in parents"; Logger.info(TAG + ": isFolderExists(): Query= " + query); request = request.setQ(query); FileList files = request.execute(); Logger.info(TAG + ": isFolderExists(): List Size =" + files.getItems().size()); if (files.getItems().size() == 0) //if the size is zero, then the folder doesn't exist return null; else //since google drive allows to have multiple folders with the same title (name) //we select the first file in the list to return return files.getItems().get(0); } 

用于在givien父项引用中创建文件夹的函数,如果列表为空,则该文件夹将在google驱动器的根目录中创建。

 /** * * @param service google drive instance * @param title the folder's title * @param listParentReference the list of parents references where you want the folder to be created, * if you have more than one parent references, then a folder will be created in each one of them * @return google drive file object * @throws IOException */ private File createFolder(Drive service,String title,List listParentReference) throws IOException { File body = new File(); body.setTitle(title); body.setParents(listParentReference); body.setMimeType("application/vnd.google-apps.folder"); File file = service.files().insert(body).execute(); return file; } 

第三个函数用于创建文件夹的目录路径,没有重复的谷歌驱动器。 为了防止谷歌驱动器中的重复文件夹,该function将在创建文件夹之前检查该文件夹是否存在。

 /** * * @param service google drive instance * @param titles list of folders titles * ie if your path like this folder1/folder2/folder3 then pass them in this order createFoldersPath(service, folder1, folder2, folder3) * @return parent reference of the last added folder in case you want to use it to create a file inside this folder. * @throws IOException */ private List createFoldersPath(Drive service,String...titles) throws IOException { List listParentReference = new ArrayList(); File file = null; for(int i=0;i