2014-02-21 41 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