Android驱动器api下载文件

Android驱动器api下载文件,android,google-drive-api,Android,Google Drive Api,我已成功使用在Google Drive中创建或修改文件。现在我需要将文件下载到设备的外部存储器中。我可以读取文件的内容,并且可以保存它。但当我试图在桌面上打开它时,该文件已损坏 @Override protected Void doInBackground(Void... params) { mBusy = true; ArrayList<ContentValues> cvs = GDAA.searchDB(UT.FILE_NAME)

我已成功使用在Google Drive中创建或修改文件。现在我需要将文件下载到设备的外部存储器中。我可以读取文件的内容,并且可以保存它。但当我试图在桌面上打开它时,该文件已损坏

    @Override
    protected Void doInBackground(Void... params) {
        mBusy = true;
         ArrayList<ContentValues> cvs = GDAA.searchDB(UT.FILE_NAME);
                if (cvs != null) for (ContentValues cv : cvs) {
                    String gdid = cv.getAsString(UT.GDID);
                    System.out.println("ID..... " + gdid);
                     byte[] buf = GDAA.read(gdid);
                     String str = buf == null ? "" : new String(buf);
                     File fl = UT.str2File(str, "myfile.db");


                        }
    ----------------------------------------------
    static File str2File(String str, String name) {
    if (str == null) return null;
    byte[] buf = str.getBytes();

    File fl = new File(Environment.getExternalStorageDirectory(), name);

    if (fl == null) return null;
    BufferedOutputStream bs = null;
    try {
      bs = new BufferedOutputStream(new FileOutputStream(fl));
      bs.write(buf);
    } catch (Exception e) { le(e); }
    finally {
      if (bs != null) try {
        bs.close();
      } catch (Exception e) { le(e); }
    }
    return fl;
  }

    ----------------------------------------------
    static byte[] read(String id) {
        byte[] buf = null;
        if (mGAC != null && mGAC.isConnected() && id != null) try {
            DriveFile df = Drive.DriveApi.getFile(mGAC, DriveId.decodeFromString(id));
            DriveContentsResult rslt = df.open(mGAC, DriveFile.MODE_READ_ONLY, null).await();
            if ((rslt != null) && rslt.getStatus().isSuccess()) {
                DriveContents cont = rslt.getDriveContents();
                buf = UT.is2Bytes(cont.getInputStream());
                cont.discard(mGAC);    // or cont.commit();  they are equiv if READONLY
            }
        } catch (Exception e) {
            UT.le(e);
        }
        return buf;
    }
@覆盖
受保护的Void doInBackground(Void…参数){
mBusy=true;
ArrayList cvs=GDAA.searchDB(UT.FILE\u名称);
如果(cvs!=null)(ContentValues cv:cvs){
字符串gdid=cv.getAsString(UT.gdid);
System.out.println(“ID…”+gdid);
字节[]buf=GDAA.read(gdid);
字符串str=buf==null?“:新字符串(buf);
File fl=UT.str2文件(str,“myfile.db”);
}
----------------------------------------------
静态文件str2文件(字符串str,字符串名称){
if(str==null)返回null;
byte[]buf=str.getBytes();
File fl=新文件(Environment.getExternalStorageDirectory(),name);
如果(fl==null)返回null;
BufferedOutputStream bs=null;
试一试{
bs=新的缓冲输出流(新的文件输出流(fl));
学士学位(buf);
}捕获(例外e){le(e);}
最后{
如果(bs!=null),请尝试{
bs.close();
}捕获(例外e){le(e);}
}
返回fl;
}
----------------------------------------------
静态字节[]读取(字符串id){
字节[]buf=null;
如果(mGAC!=null&&mGAC.isConnected()&&id!=null)尝试{
DriveFile df=Drive.DriveApi.getFile(mGAC,DriveId.decodeFromString(id));
DriveContentsResult rslt=df.open(mGAC,DriveFile.MODE_只读,null).wait();
if((rslt!=null)&&rslt.getStatus().issucess()){
DriveContents cont=rslt.getDriveContents();
buf=UT.is2字节(cont.getInputStream());
cont.discard(mGAC);//或cont.commit();如果为只读,则它们是等价的
}
}捕获(例外e){
UT.le(e);
}
返回buf;
}
这对我来说很有用:

 @Override
    protected String doInBackground(String... params) {
        try {
            //connecting to url
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            if (!rootDir.exists()) {
                rootDir.mkdirs();
            }

            //lenghtOfFile is used for calculating download progress
            int lenghtOfFile = c.getContentLength();

            //this is where the file will be seen after the download
            FileOutputStream f = new FileOutputStream(new File(rootDir, fileName));
            //file input is from the url
            InputStream in = c.getInputStream();


            //here’s the download code
            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; //total = total + len1
                f.write(buffer, 0, len1);
            }
            f.close();

        } catch (Exception e) {
            Log.d(LOG_TAG, e.getMessage());

        }

        return null;
    }

用扩展名保存文件。我也一样


例如,如果您的文件名是xyz,并且您保存时没有扩展名,那么如果您保存扩展名为xyz.pdf的文件,有时会出现问题,您不应该遇到此问题

使用此代码从google drive下载

您只需要传递要保存在sd卡上的驱动器ID和文件名

 private void DownloadFile(final DriveId driveId, final File filename) {
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                if (!filename.exists()) {
                    try {
                        filename.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);

            }

            @Override
            protected Boolean doInBackground(Void... params) {
                DriveFile file = Drive.DriveApi.getFile(
                        GapiClient, driveId);
                file.getMetadata(GapiClient)
                        .setResultCallback(metadataRetrievedCallback);
                DriveApi.DriveContentsResult driveContentsResult = file.open(
                        GapiClient,
                        DriveFile.MODE_READ_ONLY, null).await();
                DriveContents driveContents = driveContentsResult
                        .getDriveContents();
                InputStream inputstream = driveContents.getInputStream();

                try {
                    FileOutputStream fileOutput = new FileOutputStream(filename);

                    byte[] buffer = new byte[1024];
                    int bufferLength = 0;
                    while ((bufferLength = inputstream.read(buffer)) > 0) {
                        fileOutput.write(buffer, 0, bufferLength);
                    }
                    fileOutput.close();
                    inputstream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return true;
            }

        };
        task.execute();
    }

    private ResultCallback<MetadataResult> metadataRetrievedCallback = new ResultCallback<MetadataResult>() {
        @Override
        public void onResult(MetadataResult result) {
            if (!result.getStatus().isSuccess()) {
                return;
            }
            metadata = result.getMetadata();
        }
    };
private void下载文件(最终DriveId DriveId,最终文件名){
AsyncTask任务=新建AsyncTask(){
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
如果(!filename.exists()){
试一试{
filename.createNewFile();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
@凌驾
受保护的void onPostExecute(布尔结果){
super.onPostExecute(结果);
}
@凌驾
受保护的布尔doInBackground(Void…params){
DriveFile file=Drive.DriveApi.getFile(
GapiClient,driveId);
file.getMetadata(GapiClient)
.setResultCallback(metadataRetrievedCallback);
DriveApi.DriveContentsResult DriveContentsResult=file.open(
加皮客户,
DriveFile.MODE_只读,null).await();
DriveContents DriveContents=driveContentsResult
.getDriveContents();
InputStream InputStream=driveContents.getInputStream();
试一试{
FileOutputStream fileOutput=新的FileOutputStream(文件名);
字节[]缓冲区=新字节[1024];
int bufferLength=0;
而((bufferLength=inputstream.read(buffer))>0){
fileOutput.write(buffer,0,bufferLength);
}
fileOutput.close();
inputstream.close();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回true;
}
};
task.execute();
}
私有ResultCallback metadataRetrievedCallback=新ResultCallback(){
@凌驾
公共void onResult(MetadataResult){
如果(!result.getStatus().issucess()){
返回;
}
metadata=result.getMetadata();
}
};

您必须创建ByteArrayOutputStream而不是FileOutputStream。如何根据driveId获取文件名?有什么想法吗?我想您可以从这一行获取文件>>DriveFile file=Drive.DriveAPi.getFile(GapClient,driveId);请浏览文件,我希望你能得到文件名。Drive.DriveApi不推荐使用。@LubošStaráček我在2016年就做了。如果你找到了一种新的方法,请更新答案……如果我有时间查看,我一定会更新答案。谢谢。不过,这是Android的一个文档记录很差的领域,但我会更新如果我找到答案,我就吃了。