简体   繁体   中英

Google drive api saving to file

I am trying to save a file by using google drive api .

Code that I am using to save file at the moment looks following:

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

This is the part that is supposed to get the file contents:

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

I assume, you want to save a text file ('json.txt') to Google Drive and your code applies to Android.

First, you do not indicate what API you decided to use, the REST Api or the GDAA .

Starting with java.io.File as an input (your first code block), here are code snippets for both the GDAA and REST Apis.

GDAA: (you may consider turning the 'await' methods into callbacks, or you have to wrap it in non-UI thread)

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: (you have to wrap it in non-UI thread)

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;
  }

Wider context of these methods can be found here and here if you care to dig deeper.

Good Luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM