2011-12-13 66 views
1

我已經搜索了很多關於此問題的信息。我的電話沒有固定。我想以編程方式將數據庫文件從應用程序的資產文件夾複製到我的Android設備的/ system/usr。所以我可以從那裏訪問數據庫文件,並檢查我的應用程序的用戶是否能夠升級數據庫。我知道,我必須要改變在下面的代碼「outFileName」和「的OutputStream」,但我不完全知道如何指定/系統正/下面的代碼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()); 
        } 

      } 
      }); 

感謝有什麼建議麼。

回答

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(); 
} 
1

這是不可能的,除非你的設備是固定的。但是我不明白你爲什麼需要這樣做。也許如果你能告訴你想做什麼,這裏的某個人可以幫助你找到解決方案。

+0

甚至編程這是不可能的?我的應用程序允許用戶在運行應用程序時向sqlite數據庫添加新行。我想查看用戶是否真的能夠添加新行。我想這可以使用SQL查詢完成,例如:http://stackoverflow.com/questions/4017903/get-last-inserted-value-from-sqlite-database-android –

+0

您可以從資產文件夾複製到數據/data/com.yourname/databases而不是system/usr。前者會解決你的問題嗎? – silleknarf

+0

無法將文件複製到要放置的位置(/ system/usr)。但是,您當然可以將其複製到應用程序專用(內部)存儲或設備外部存儲。有關更多信息,請參閱[this](http://developer.android.com/guide/topics/data/data-storage.html#filesInternal)。 – Anasthase

相關問題