谷歌硬盘api保存到文件

时间:2015-09-14 15:09:13

标签: java android google-drive-api google-drive-android-api

我正在尝试使用google drive api保存文件。

我目前用于保存文件的代码如下所示:

 final java.io.File file = new java.io.File(Environment.getExternalStorageDirectory() + java.io.File.separator + "Json.txt");
        try {
            file.createNewFile();
            if (file.exists()) {
                final FileWriter fileWriter = new FileWriter(file);
                final String json = gson.toJson(filesEvent);
                fileWriter.write(json);
                fileWriter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

这是应该获取文件内容的部分:

final StringBuilder sb = getStringBuilder(new FileReader(Environment.getExternalStorageDirectory() + java.io.File.separator + "Json.txt"));
            File file  = gson.fromJson(sb.toString(), File.class);

1 个答案:

答案 0 :(得分:2)

我认为,您要将文本文件(' json.txt')保存到Google云端硬盘,您的代码适用于Android。

首先,您没有指明您决定使用哪种API,REST Api或GDAA

java.io.File 开始作为输入(您的第一个代码块),这里是GDAA和REST Apis的代码片段。

GDAA:(您可以考虑将' await'方法转换为回调,或者您必须将其包装在非UI线程中)

dependencies {
  ...
  compile 'com.google.android.gms:play-services:7.8.0'
}

  com.google.android.gms.common.api.GoogleApiClient mGAC;
  ... 
  /**********************************************************************
   * create file/folder in GOODrive
   * @param prnId  parent's ID, (null for root)
   * @param titl  file name
   * @param mime  file mime type
   * @param file  file (with content) to create
   * @return      file id  / null on fail
   */
  DriveId createFile(DriveId prnId, String titl, String mime, File file) {
    DriveId dId = null;
    if (mGAC != null && mGAC.isConnected() && titl != null && mime != null && file != null) {
      DriveFolder pFldr = (prnId == null) ?
        Drive.DriveApi.getRootFolder(mGAC): Drive.DriveApi.getFolder(mGAC, prnId);
      if (pFldr == null) return null; //----------------->>>

      MetadataChangeSet meta;
      DriveContentsResult r1 = Drive.DriveApi.newDriveContents(mGAC).await();
      if (r1 == null || !r1.getStatus().isSuccess()) return null; //-------->>>

      meta = new Builder().setTitle(titl).setMimeType(mime).build();
      DriveFileResult r2 = pFldr.createFile(mGAC, meta, r1.getDriveContents()).await();
      DriveFile dFil = r2 != null && r2.getStatus().isSuccess() ? r2.getDriveFile() : null;
      if (dFil == null) return null; //---------->>>

      r1 = dFil.open(mGAC, DriveFile.MODE_WRITE_ONLY, null).await();
      if ((r1 != null) && (r1.getStatus().isSuccess()))  {
        Status stts = fileToCont(r1.getDriveContents(), file).commit(mGAC, meta).await();
        if ((stts != null) && stts.isSuccess()) {
          MetadataResult r3 = dFil.getMetadata(mGAC).await();
          if (r3 != null && r3.getStatus().isSuccess()) {
            dId = r3.getMetadata().getDriveId();
          }
        }
      }
    }
    return dId;
  }

  DriveContents fileToCont(DriveContents driveContents, File file) {
    OutputStream oos = driveContents.getOutputStream();
    if (oos != null) try {
      InputStream is = new FileInputStream(file);
      byte[] buf = new byte[4096];
      int c;
      while ((c = is.read(buf, 0, buf.length)) > 0) {
        oos.write(buf, 0, c);
        oos.flush();
      }
    } catch (Exception e)  { UT.le(e);}
    finally {
      try {
        oos.close();
      } catch (Exception ignore) {
      }
    }
    return driveContents;
  }

REST Api:(您必须将其包装在非UI线程中)

dependencies {
  ...
  compile 'com.google.apis:google-api-services-drive:v2-rev105-1.17.0-rc'
  compile 'com.google.api-client:google-api-client-android:1.20.0'
  compile 'com.google.http-client:google-http-client-gson:1.20.0'
}

  com.google.api.services.drive.Drive mGOOSvc;
  ...
  /***************************************************************
   * create file/folder in GOODrive
   * @param prnId  parent's ID, (null or "root") for root
   * @param titl  file name
   * @param mime  file mime type
   * @param file  file (with content) to create
   * @return      file id  / null on fail
   */
  static String createFile(String prnId, String titl, String mime, java.io.File file) {
    String rsId = null;
    if (mGOOSvc != null  && titl != null && mime != null && file != null) try {
      File meta = new File();
      meta.setParents(Arrays.asList(new ParentReference().setId(prnId == null ? "root" : prnId)));
      meta.setTitle(titl);
      meta.setMimeType(mime);

      File gFl = mGOOSvc.files().insert(meta, new FileContent(mime, file)).execute();
      if (gFl != null)
        rsId = gFl.getId();
    }
    catch (UserRecoverableAuthIOException uraIOEx) {
      // handle  uraIOEx;
    }
    catch (IOException e) {  
      if (e instanceof GoogleJsonResponseException) {
        if (404 == ((GoogleJsonResponseException)e).getStatusCode())
          // handle  error;
      }
    } catch (Exception e) {
      // handle  error;
    }
    return rsId;
  }

如果你想深入挖掘,可以找到这些方法的更广泛的上下文herehere

祝你好运