以编程方式从应用程序的资产文件夹中复制数据库文件

时间:2011-12-13 12:35:43

标签: android ddms android-assets

我已经搜索过很多关于这个问题的帖子。我的手机还没根。我想以编程方式将数据库文件从我的应用程序的资产文件夹复制到我的Android设备的/ system / usr。这样我就可以从那里访问数据库文件并检查我的应用程序的用户是否能够升级数据库。我知道我必须在以下代码中更改'outFileName'和“outputStream”,但我不确定如何在以下代码中指定/ sytem / usr的输出路径:

copyDBfromassetstodevicedrive.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                try {
                    // Open your local db as the input stream
                    InputStream myInput = myContext.getAssets().open("myDB.db");

                    // Path to the just created empty db
                    String outFileName = "/data/data/your app package name/databases/database file name";

                    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();
                    } 
                    catch (Exception e) 
                    {
                    Log.e("error", e.toString());
                    }

            }
          });

感谢您的任何建议。

2 个答案:

答案 0 :(得分:1)

除非您的设备已植根,否则无法进行此操作。但是我不明白为什么你需要这样做。也许如果你能告诉你想做什么,这里有人可以帮你找到解决方案。

答案 1 :(得分:0)

private static String DB_PATH = Environment.getDataDirectory()+"/data/package-name/databases/";

private void copyDataBase() throws IOException
{


    // Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty d inb
    String outFileName = DB_PATH + DB_NAME;

    // 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();

    //Copy successful
    outFileName = DB_PATH + DB_SUCCESS;
    myOutput = new FileOutputStream(outFileName);
    myOutput.write(1);
    myOutput.flush();
    myOutput.close();
}
相关问题