android - 从没有开启Root的设备中的 Assets 文件夹复制数据库

标签 android android-emulator android-ndk rooted-device

我正在尝试将数据库从 Assets 文件夹复制到设备。此代码在模拟器和根设备上运行良好。我只是想知道它是否会在没有开启Root的设备上产生任何问题,或者它会起作用。

private void StoreDatabase() {
    File DbFile = new File(
            "data/data/packagename/DBname.sqlite");
    if (DbFile.exists()) {
        System.out.println("file already exist ,No need to Create");
    } else {
        try {
            DbFile.createNewFile();
            System.out.println("File Created successfully");
            InputStream is = this.getAssets().open("DBname.sqlite");
            FileOutputStream fos = new FileOutputStream(DbFile);
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = is.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            System.out.println("File succesfully placed on sdcard");
            // Close the streams
            fos.flush();
            fos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

最佳答案

这肯定适用于所有设备和模拟器,无需root。

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */
private void copyDataBase(String dbname) throws IOException {
    // Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(dbname);
    // Path to the just created empty db
    File outFileName = myContext.getDatabasePath(dbname);
    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);
    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }
    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

关于android - 从没有开启Root的设备中的 Assets 文件夹复制数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10738623/

相关文章:

android - 如何使用 NDK 17 为 64 位 Android 构建 OpenSSL 1.1.1

android - AIDE OpenGL es 2.0 三角形无法渲染

Android 模拟器在来电时断开连接

android - Activity 中的 onPause() 和 onStop()

java - 不幸的是应用程序已停止工作

android - 如何为具有 64 位 CPU 的设备构建 .so 二进制文件?

android - Android 中的 C++ 流。如何使用 std::ofstream 写入设备内存?

android - 应用程序运行时屏幕顶部显示带有应用程序标题的标签

java - 自定义 ArrayList 搜索问题?

android - FusedLocationProvider - 如果位置模式为 "Device Only",有什么方法可以获取位置?