无法从Android手机导出数据库

时间:2017-06-29 19:36:45

标签: java android sqlite file

我想将我的数据库导出到文件。这是我的代码。

public static void backupDatabase(Context mContext) throws IOException {
    //Open your local db as the input stream
    String DB_PATH=null;
    if(android.os.Build.VERSION.SDK_INT >= 17) {
        DB_PATH = mContext.getApplicationInfo().dataDir + "/databases/";
    } else {
        DB_PATH = "/data/data/" + mContext.getPackageName() + "/databases/";
    }
    DB_PATH=DB_PATH+"SamsungLightingApp.db";
    File dbFile = new File(DB_PATH);
    FileInputStream fis = new FileInputStream(dbFile);

    String outFileName = Environment.getExternalStorageDirectory() + "/MY DB.db";
    //Open the empty db as the output stream
    OutputStream output = new FileOutputStream(outFileName);
    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = fis.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
    //Close the streams
    output.flush();
    output.close();
    fis.close();
}
  

当我们打开FileInputStream时,它会抛出文件不存在的错误。   我总是得到FileNotFoundException

3 个答案:

答案 0 :(得分:1)

运行adb命令以检查数据库的位置。

adb shell

run-as package-name

找到数据库路径并检查它是否与程序中的路径匹配。

答案 1 :(得分:0)

使用context.getDatabasePath(dbfilename)获取数据库的文件。永远不要假设任何类型的硬编码路径。

答案 2 :(得分:0)

自API 1以来,

context.getDatabasePath("dbfilename.db")已经存在。如果数据库文件退出,它肯定会有效。它会返回一个文件。