2016-07-31 176 views
0

我想創建一個臨時數據庫,這是代碼:重複的默認數據庫到臨時數據庫

String PATH = "/data/data/" + appContext.getPackageName() + "/databases/"; 
      List<File> files = getListFiles(new File(PATH)); 
      //File dbFile = appContext.getDatabasePath(PreferenceConstants.TEMP_DB_DATABASE_STORE); 
      File dbFile = new File(PATH, PreferenceConstants.TEMP_DB_DATABASE_STORE); 
      FileInputStream is; 

      if (!dbFile.exists()) { 
       try { 
        dbFile.createNewFile(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      }else 
       dbFile.delete(); 
      try { 
       is = new FileInputStream(appContext.getDatabasePath(PreferenceConstants.DB_DATABASE_STORE)); 
       FileUtils.copyInputStreamToFile(is, dbFile); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

,但沒有文件被創建到數據庫文件夾,爲什麼呢?

複製後我想打開另一個數據庫,複製表並在創建的臨時數據庫中追加表。

編輯

非常簡單的方法:

DatabaseHelper dbIng = new DatabaseHelper(appContextDialog, "temp_database.db"); 
dbIng.closeDB(); 

回答

1

這是我使用的導入和導出數據庫的內容: 不要忘了權限。

public void exportDatabase(){ 
    try 
    { 
     File sd = Environment.getExternalStorageDirectory(); 
     File data = Environment.getDataDirectory(); 

     String currentDBPath = "//data//MY.PACKAGE.NAME//databases//MY_DATABASE_NAME"; 
     String backupDBPath = "MY_DATABASE_FILE.db"; 
     File currentDB = new File(data, currentDBPath); 
     File backupDB = new File(sd, backupDBPath); 

     FileChannel src = new FileInputStream(currentDB).getChannel(); 
     FileChannel dst = new FileOutputStream(backupDB).getChannel(); 
     dst.transferFrom(src, 0, src.size()); 
     src.close(); 
     dst.close(); 

     Toast.makeText(c, c.getResources().getString(R.string.exporterenToast), Toast.LENGTH_SHORT).show(); 
    } 
    catch (Exception e) { 
     Toast.makeText(c, c.getResources().getString(R.string.portError), Toast.LENGTH_SHORT).show(); 
     Log.d("Main", e.toString()); 
    } 
} 

public void importDatabase(){ 
    try 
    { 
     File sd = Environment.getExternalStorageDirectory(); 
     File data = Environment.getDataDirectory(); 

     String currentDBPath = "//data//" + "MY.PACKAGE.NAME" + "//databases//" + "MY_DATABASE_NAME"; 
     String backupDBPath = "MY_DATABASE_FILE.db"; 
     File backupDB = new File(data, currentDBPath); 
     File currentDB = new File(sd, backupDBPath); 

     FileChannel src = new FileInputStream(currentDB).getChannel(); 
     FileChannel dst = new FileOutputStream(backupDB).getChannel(); 
     dst.transferFrom(src, 0, src.size()); 
     src.close(); 
     dst.close(); 
     Toast.makeText(c, c.getResources().getString(R.string.importerenToast), Toast.LENGTH_LONG).show(); 
    } 
    catch (Exception e) { 
     Toast.makeText(c, c.getResources().getString(R.string.portError), Toast.LENGTH_SHORT).show(); 
    } 
}