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

5

我一直在尝试将一个纯文本文件保存到Android上Google Drive中的特定文件夹中。

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

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

我已经能够使用以下代码在Google Drive的基础目录中创建一个新文件夹:

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

我也可以使用以下代码列出用户Google Drive帐户中的所有文件夹:

      List<File> 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 Drive中的文件夹中。

3个回答

6

您需要使用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();

你如何获取 parentId 的值? - Kees de Kooter
如果你知道要存储在哪里,那就非常简单明了。 - the100rabh
服务是哪种类型的对象? - Solanki Kamlesh

1
如果您想要在Google Drive中的特定文件夹中插入文件,请按照以下步骤操作。我们假设已从Drive检索到所有文件夹,现在我将在列表中的第一个文件夹中插入一个空文件。
         //Getting Folders from the DRIVE
List<File> 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();

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


0

步骤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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接