2014-02-21 40 views
1

我正在創建一個使用現成的SQLiteDatabase的應用程序。我正在給用戶選擇將數據庫複製到SD卡或手機內存中。將數據庫複製到手機內存時,以下代碼可以很好地工作。 26.5 MB數據庫完全複製到手機內存中。但是,如果使用相同的代碼複製SD卡,則只複製數據庫的一部分,即只複製名爲android_metadata的一個表。複製到SD卡時數據庫部分複製

private void copyDatabase(String storage) { 

    try { 
     //DB_NAME is defined in the class 
     //DB_PATH refers to the phone directory path. 
     InputStream in = myContext.getAssets().open(DB_NAME); 
     File sd = Environment.getExternalStorageDirectory(); 
     File sdCardPath = new File(sd, DB_NAME); 
     File phonePath = new File(DB_PATH + DB_NAME); 
     OutputStream os = null; 
     if (storage.equalsIgnoreCase("sd")) 
      os = new FileOutputStream(sdCardPath); 
     else if (storage.equalsIgnoreCase("phone")) 
      os = new FileOutputStream(phonePath); 
     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = in.read(buffer)) != -1) { 
      os.write(buffer, 0, length); 

     } 

     os.flush(); 
     os.close(); 
     in.close(); 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

問題是,雖然數據庫是在SD卡內存中創建的,但是不會複製完整的數據庫。這樣創建的數據庫只有3.4 Mb的大小,而原始數據庫的大小是26.5 Mb,我通過Eclipse中的文件資源管理器視圖檢查了這個數據庫的大小。

有什麼建議嗎?

編輯: 由於我直接從assets文件夾複製數據庫,我才能獲取FileInputStreamFileChannel對象。我只能從assets資源中獲得一個InputStream對象。

回答

0

請儘量給定的功能,希望它會幫助你

public void copyDatabse(String databaseName) { 
     try { 
      File sd = Environment.getExternalStorageDirectory(); 
      File data = Environment.getDataDirectory(); 

      if (sd.canWrite()) { 
       String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+""; 
       String backupDBPath = "backupname.db"; 
       File currentDB = new File(data, currentDBPath); 
       File backupDB = new File(sd, backupDBPath); 

       if (currentDB.exists()) { 
        FileChannel src = new FileInputStream(currentDB).getChannel(); 
        FileChannel dst = new FileOutputStream(backupDB).getChannel(); 
        dst.transferFrom(src, 0, src.size()); 
        src.close(); 
        dst.close(); 
       } 
      } 
     } catch (Exception e) { 

     } 
    } 

,並呼籲爲copyDatabse("databasename");

還請訪問

Trying to Copy SQLite DB from data to SD card

+0

我搜索了谷歌並偶然發現了您提供的鏈接。但兩個問題的區別在於我直接從'assets'文件夾複製數據庫,因此無法獲得'FileInputStream'。另一方面,另一個問題從手機存儲器複製數據。 – Rajat

+0

哦,好吧,我會試着回答一些問題,並且會回來 –

0

此代碼應該做的工作:

void copyDataBase() throws IOException { 

     String outFileName = DB_PATH + DB_NAME; 

     OutputStream myOutput = new FileOutputStream(outFileName); 

     byte[] buffer = new byte[1024]; 
     int length; 

     InputStream myInput = myContext.getAssets().open("mydb.sqlite"); 
     while ((length = myInput.read(buffer)) > 0) { 
      myOutput.write(buffer, 0, length); 
     } 
     myInput.close(); 

     myOutput.flush(); 
     myOutput.close(); 

    } 

outFileName將保存位置到您想要在SD卡上存儲的位置

+0

不,這沒有奏效,結果和我使用我的代碼一樣。此外,我不知道你的代碼和我的代碼是不同的。實質上,它們都是相同的。 – Rajat