使用Google Drive SDK将文件保存在特定文件夹中

我一直在尝试将纯文本文件保存到Android上的Google云端硬盘中的特定文件夹中。

到目前为止,使用Google云端硬盘上的文档和快速入门指南 ,我已经能够做一些正确的方向,首先我能够创建纯文本文件:

File body = new File(); body.setTitle(fileContent.getName()); body.setMimeType("text/plain"); File file = service.files().insert(body, textContent).execute(); 

我已经能够在Google云端硬盘的基本目录中创建一个新文件夹:

  File body = new File(); body.setTitle("Air Note"); body.setMimeType("application/vnd.google-apps.folder"); File file = service.files().insert(body).execute(); 

我还能够列出用户的Google云端硬盘帐户中的所有文件夹:

  List files = service.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'").execute().getItems(); for (File f : files) { System.out.println(f.getTitle() + ", " + f.getMimeType()); } 

但是我对如何将文本文件保存到Google云端硬盘中的文件夹感到困惑。

您需要使用parent参数将文件放入使用insert的文件夹中。 有关详细信息, 请访问https://developers.google.com/drive/v2/reference/files/insert

像这样的东西

 File body = new File(); body.setTitle(fileContent.getName()); body.setMimeType("text/plain"); body.setParents(Arrays.asList(new File.ParentReference().setId(parentId)); File file = service.files().insert(body, textContent).execute(); 

如果要在Google云端硬盘中的特定文件夹中插入文件,请按以下步骤操作。 让我们假设我们已经从驱动器中检索了所有文件夹,现在我将在列表的第一个文件夹中插入一个空文件,所以

  //Getting Folders from the DRIVE List files = mService.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'").execute().getItems(); File f =files.get(1)//getting first file from the folder list body.setTitle("MyEmptyFile"); body.setMimeType("image/jpeg"); body.setParents(Arrays.asList(new ParentReference().setId(f.getId()))); com.google.api.services.drive.model.File file = mService.files().insert(body).execute(); 

现在,这将在文件夹中创建一个空文件,该文件位于检索文件列表的顶部。

第1步:创建一个文件夹

 File body1 = new File(); body1.setTitle("cloudbox"); body1.setMimeType("application/vnd.google-apps.folder"); File file1 = service.files().insert(body1).execute(); 

第2步:插入您的文件

 File body2 = new File(); body2.setTitle(fileContent.getName()); body2.setMimeType("text/plain"); body2.setParents(Arrays.asList(new ParentReference().setId(file1.getId()))); File file2 = service.files().insert(body2, mediaContent).execute();