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

时间:2013-01-20 07:50:56

标签: java android google-drive-api

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

到目前为止,在Google云端硬盘上使用文档和QuickStart Guide,我已经能够做一些正确的方向,首先我能够创建一个纯文本文件:

  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<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云端硬盘中的文件夹感到困惑。

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:1)

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

         //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();

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

答案 2 :(得分:1)

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