web-dev-qa-db-ja.com

データベースファイルをsdcardにコピーしますandroid

このコードでデータベースファイルを取得しています

  File dbFile=getDatabasePath("EdsysEyfsDB.db");
               Log.v("database name checking", dbFile.toString());

このデータベースファイルをsdcardにコピーして、そのための操作を実行できるようにします。しかし、私はそれに対して何の操作もできません。以下のコードはSDカードへのコピーに使用しています

         if (dbFile.exists()) {
                       InputStream inStream = new FileInputStream(dbFile);
                       String file = Environment.getExternalStorageDirectory().getPath()
                            +"/" + "database.db";
                       Log.d("file name checking in  dbFilecondition", file);
                       FileOutputStream fs = new FileOutputStream(file);
                       byte[] buffer = new byte[1444];
                       while ((byteread = inStream.read(buffer)) != -1) {
                           bytesum += byteread;
                           fs.write(buffer, 0, byteread);
                       }
                       inStream.close();
                       fs.close();
                   }

しかし、私はこの状態にはなりません。データベースファイル名はLogCatに正しく表示されます。私はすでにファイルの読み取りと書き込みを許可しています。

16
Ameer

これがあなたを助けることを願ってこの希望を試してください

public void exportDatabse(String databaseName) {
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
                String backupDBPath = "backupname.db";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch (Exception e) {

        }
    }

呼び方

exportDatabse("YourDBName");

注:

<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />を使用して外部ストレージに書き込む権限を追加することを忘れないでください。そうしないと、sd.canWrite()がfalseになります。

52
Biraj Zalavadia

残念ながら、受け入れられた回答は最近では関係ありません。問題は、誤って検出されたSDパスにあります。実際のパスは通常、モバイルデバイスのメーカーによって異なり、モデルによって異なる場合があります。

Androidバージョンとは関係なくSDへの実際のパスを検出する簡単な解決策を見つけました。ContextCompat.getExternalFilesDirs[1]には関連する文字列が含まれています。 Android 6から9バージョンのデバイスでテスト済み

2番目の問題はDBへの定義済みパスです。次のように、パッケージ名の前に「data/data /」が含まれている必要があります。

これが私のプロジェクトのコードの一部です

String sdPath;

    private boolean isSDPresent(Context context) {

        File[] storage = ContextCompat.getExternalFilesDirs(context, null);
        if (storage.length > 1 && storage[0] != null && storage[1] != null) {
            sdPath = storage[1].toString();
            return true;
        }
        else
          return false;
    }


    private boolean isContextValid(Context context) {
        return context instanceof Activity && !((Activity) context).isFinishing();
    }

    public boolean exportDatabase(Context context, String localDbName, String backupDbName) {
        if (isContextValid(context))
            try {
                if (!SettingsFile.isSDPresent(context)) {
                    Log.e(TAG, "SD is absent!");
                    return false;
                }

                File sd = new File(sdPath); 

                if (sd.canWrite()) {

                    File currentDB = new File("/data/data/" + context.getPackageName() +"/databases/", localDbName); 
                    File backupDB = new File(sd,  backupDbName);

                    if (currentDB.exists()) {
                        FileChannel src = new FileInputStream(currentDB).getChannel();
                        FileChannel dst = new FileOutputStream(backupDB).getChannel();
                        dst.transferFrom(src, 0, src.size());
                        src.close();
                        dst.close();
                    }
                }
                else {
                    Log.e(TAG, "SD can't write data!");
                    return false;
                }
            } catch (Exception e) {

            }
        else {
            Log.e(TAG, "Export DB: Context is not valid!");
            return false;
        }

        return true;
    }
0
Dimon