17

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

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

このデータベースファイルをSDカードにコピーして、そのための操作を実行できるようにします。しかし、私はそれに対して操作を行うことはできません。以下のコードは、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 でちゃんと来ています。私はすでにファイルの読み取りと書き込みの許可を与えています。

4

2 に答える 2

54

これが役立つことを願って試してみてください

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 になります。

于 2013-09-30T12:01:08.450 に答える