簡體   English   中英

如何從 GDrive 恢復文件?

[英]How to restore file from GDrive?

我正在制作一個應用程序,它將其 SQLite 數據庫備份存儲在 GDrive 上。 我成功登錄並上傳驅動器中的文件,但未能恢復它。 以下是代碼。 我使用 SQLiteDatabase 來存儲 fileID,以便在更新和恢復時需要它時可以使用它。 我正在尋找一種使用 FileID 進行恢復的方法。 file.getDownloadUrl() 和 file.getContent() 發生錯誤。

 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 文件就像

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'

據我所知,下載 URL 僅在 Google 驅動器 api v2 中可用,在 V3 中不可用。

短暫下載 URL 文件。 此字段僅針對內容存儲在 Google Drive 中的文件填充; 它不會為 Google Docs 或快捷方式文件填充。

我認為它不是很穩定,因為並非所有文件類型都會返回下載 url。

使用 Google Drive v3,您應該使用 stream 下載文件。

String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
    .executeMediaAndDownloadTo(outputStream);

這應該適用於還原。 讓我知道它是否沒有,我會看看自從我嘗試恢復以來已經有一段時間了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM