我可以使用CreateFileActivity.java在Google云端硬盘中创建一个文件。但我想一次将两个或多个文件上传到谷歌硬盘。如何在谷歌硬盘中创建多个文件的android?
答案 0 :(得分:0)
假设您的Android设备上有多个文件,由具有已知名称(标题)和mime类型的 java.io.File 对象表示:
java.io.File[] files = {...};
String[] names[] = {...};
String[] mimes[] = {...};
您可以使用此构造在Google云端硬盘中创建一组文件(例如,在根目录中):
com.google.android.gms.common.api.GoogleApiClient mGooApiClient;
void foo() {
for (int i = 0; i < files.length; i++) {
createFile(null, names[i], mimes[i], files[i]);
}
}
/***********************************************************************
* create file in GOODrive
* @param pFldr parent's ID, (null for root)
* @param titl file name
* @param mime file mime type
* @param file java.io.File (with content) to create
*/
void createFile(DriveFolder pFldr, final String titl, final String mime, final File file) {
DriveId dId = null;
if (mGooApiClient != null && mGooApiClient.isConnected() && titl != null && mime != null && file != null) try {
final DriveFolder parent = pFldr != null ? pFldr : Drive.DriveApi.getRootFolder(mGooApiClient);
if (pFldr == null) return; //----------------->>>
Drive.DriveApi.newDriveContents(mGAC).setResultCallback(new ResultCallback<DriveContentsResult>() {
@Override
public void onResult(DriveContentsResult driveContentsResult) {
DriveContents cont = driveContentsResult != null && driveContentsResult.getStatus().isSuccess() ?
driveContentsResult.getDriveContents() : null;
if (cont != null) try {
OutputStream oos = cont.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();
}
}
finally { oos.close();}
MetadataChangeSet meta = new Builder().setTitle(titl).setMimeType(mime).build();
parent.createFile(mGooApiClient, meta, cont).setResultCallback(new ResultCallback<DriveFileResult>() {
@Override
public void onResult(DriveFileResult driveFileResult) {
DriveFile dFil = driveFileResult != null && driveFileResult.getStatus().isSuccess() ?
driveFileResult.getDriveFile() : null;
if (dFil != null) {
// save dFil, report success
} else {
// handle error
}
}
});
} catch (Exception e) {e.printStackTrace();}
}
});
} catch (Exception e) { e.printStackTrace(); }
}
不要忘记保存DriveFile(或DriveId)或创建的文件。
祝你好运