使用 Google 驱动器 API 创建文件的本地副本

Making local copy of file using Google Drive API

我想使用 Google 驱动器 android Api.[= 制作存在于 Google 驱动器上的“.ppt”文件的本地副本(外部存储) 13=]

我正在读取一个字节并将其写入我的本地文件。但是当我试图打开它时,它显示文件已损坏。请帮助我解决问题。

final DriveFile file = Drive.DriveApi.getFile(getClient(), fileid);
final Metadata[] metadata = new Metadata[1];

file.getMetadata(getClient())
.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
    @Override
    public void onResult(DriveResource.MetadataResult metadataResult) {
        metadata[0] = metadataResult.getMetadata();
        L.b(EditorWindow.this, metadata[0].getMimeType(), 0);
    }
});

file.open(getClient(), DriveFile.MODE_READ_ONLY, null)
.setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
    @Override
    public void onResult(DriveApi.DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            L.c("Error in creating new file");
            return;
        }
        DriveContents contents = result.getDriveContents();
        String filename = metadata[0].getTitle();
        File localFile = new File(Environment.getExternalStorageDirectory(), filename);
        OutputStream out = null;
        InputStream in = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            in = contents.getInputStream();
            int b;
            while ( (b = in.read()) > 0) {
                out.write(b);
            }
            in.close();
            out.close();
        } catch (Exception e) {L.c("Error in writing to SD card");}
        contents.discard(getClient());
    }
});

您可以尝试将 while 条件更改为 ( (b = in.read()) >= 0) 吗?请注意,0 是要从 InputStream 中读取的有效字节。 http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()