首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从GDrive恢复文件?

如何从GDrive恢复文件?
EN

Stack Overflow用户
提问于 2020-05-17 21:20:28
回答 1查看 215关注 0票数 0

我正在制作一个应用程序,将其SQLite数据库备份存储在GDrive上。我成功地登录并上传了驱动器中的文件,但未能恢复它。下面是代码。我使用SQLiteDatabase来存储fileID,以便在更新和恢复时需要时可以使用它。我正在寻找一种方法,它将利用FileID来恢复。错误发生在file.getDownloadUrl()和file.getContent()。

代码语言:javascript
复制
 class DriveClassHelper 
{
    private final Executor mExecutor = Executors.newSingleThreadExecutor();
    private static Drive mDriveService;

    private String FileID = null;

    private static String filePath = "/data/data/com.example.gdrivebackup/databases/Data.db";


    DriveClassHelper(Drive mDriveService) 
    {
        DriveClassHelper.mDriveService = mDriveService;
    }

    // ---------------------------------- TO BackUp on Drive  -------------------------------------------

    public Task<String> createFile() 
    {
        return Tasks.call(mExecutor, () ->
                {

                    File fileMetaData = new File();
                    fileMetaData.setName("Backup");
                    java.io.File file = new java.io.File(filePath);
                    String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("application/x-sqlite-3");
                    FileContent mediaContent = new FileContent(mimeType, file);
                    File myFile = null;

                    FileID = getFileIDFromDatabase();

                    try {
                        if (FileID != null) {
                            Log.i("CALLED : ", FileID);
                            //mDriveService.files().delete().execute();
                            myFile = mDriveService.files().update(FileID, fileMetaData, mediaContent).execute();
                        } else {
                            myFile = mDriveService.files().create(fileMetaData, mediaContent).execute();
                            MainActivity.demoSQLite.insertData(myFile.getId());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (myFile == null) {
                        throw new IOException("Null Result when requesting file creation");
                    }

                    Log.i("ID:", myFile.getId());
                    return myFile.getId();
                }
        );
    }

    // -------------------------------------------------------------------------------------------------

    // ---------------------------------- TO get File ID  -------------------------------------------

    private static String getFileIDFromDatabase() 
    {
        String FileIDFromMethod = null;
        Cursor result = MainActivity.demoSQLite.getData();

        if (result.getCount() == 0) {
            Log.i("CURSOR :", "NO ENTRY");
            return null;
        } else {
            while (result.moveToNext()) {
                FileIDFromMethod = result.getString(0);
            }
            return FileIDFromMethod;
        }
    }

    // -------------------------------------------------------------------------------------------------

    // ---------------------------------- TO Restore  -------------------------------------------


    public static class Restore extends AsyncTask<Void, Void, String>
    {
        @Override
        protected String doInBackground(Void... params) {
            String fileId = null;
            try
            {
                fileId = getFileIDFromDatabase();

                if (fileId != null)
                {
                    File file = mDriveService.files().get(fileId).execute();
                    downloadFile(file);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return fileId;
        }

        private void downloadFile(File file)
        {
            InputStream mInput = null;
            FileOutputStream mOutput = null;


            if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) //Error occurs at file.getDownloadUrl()
            {
                try
                {
                    HttpResponse resp = mDriveService.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();

                    mInput = resp.getContent();
                    String outFileName = "file://" + Environment.getDataDirectory().getPath() + filePath;
                    // Log.e("com.example.myapp", "getDatabasePath="+ getDatabasePath(""));
                    //Log.e("com.example.myapp", "outFileName="+outFileName);
//                  String outFileName = "../databases/" + "Quickpay.db";
                    mOutput = new FileOutputStream(outFileName);
                    byte[] mBuffer = new byte[1024];
                    int mLength;
                    while ((mLength = mInput.read(mBuffer)) > 0)
                    {
                        mOutput.write(mBuffer, 0, mLength);
                    }
                    mOutput.flush();
                }
                catch (IOException e)
                {
                    // An error occurred.
                    e.printStackTrace();
                    // return null;
                }
                finally
                {
                    try
                    {
                        //Close the streams
                        if (mOutput != null)
                        {
                            mOutput.close();
                        }
                        if (mInput != null)
                        {
                            mInput.close();
                        }
                    }
                    catch (IOException e)
                    {
                        Log.e("com.example.myapp", "failed to close databases");
                    }
                }
            }
            else
            {
                // The file doesn't have any content stored on Drive.
                // return null;
                Log.e("com.example.myapp", "No content on Drive");
            }
        }
    }
}

Gradle文件就像

代码语言:javascript
复制
implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0')
            {
                exclude group: 'org.apache.httpcomponents'
            }
    implementation('com.google.api-client:google-api-client-android:1.26.0')
            {
                exclude group: 'org.apache.httpcomponents'
            }
    implementation 'com.google.http-client:google-http-client-gson:1.26.0'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-18 08:45:49

据我所知,下载URL只在Google v2中,而不是在V3中。

文件的短期下载网址。此字段仅用于存储在Google中的文件,而对于Google或快捷方式文件则不填充。

在我看来,这并不是很稳定,因为并非所有的文件类型都会返回下载url。

使用Google v3,您应该使用流下载文件。

代码语言:javascript
复制
String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
    .executeMediaAndDownloadTo(outputStream);

这应该适用于还原。让我知道,如果它没有,我会看看,这是一段时间以来,我尝试恢复。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61858996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档