2015-06-01 72 views
-2

我想将sqlite数据库文件保存在外部存储器中。在外部存储器中保存sqlite数据库

我编写的代码保存在如下的内部内存中。但我想在运行时提取“xxx.db”并检查我的数据库字段是否已保存。

的manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

DBHelper.java

private static String DB_PATH   = "data/data/com.example.myApp/databases/"; 
private static final String DATABASE_TABLE = "myDB"; 
private static final int DATABASE_VERSION = 1; 
private static final String DATABASE_NAME = "mydb.db"; 

public void createDatabase() throws IOException{ 

     boolean doesDbExist = checkDatabase(); 

     if(doesDbExist){ 
      Toast.makeText(ourContext, "DB Already Created", Toast.LENGTH_SHORT).show(); 
     }else{ 
      this.getReadableDatabase(); 
      try{ 
       copyDatabase(); 
      }catch(Exception e){ 
       Log.d("DBError", "Copy DB error"); 
      } 
      Toast.makeText(ourContext, "New DB created.", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    private void copyDatabase() throws IOException{ 
      //Open your local db as the input stream 
      InputStream myInput  = ourContext.getAssets().open(DATABASE_NAME); 

      // Path to the just created empty db 
      String outFileName  = DB_PATH + DATABASE_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 len; 

      while ((len = myInput.read(buffer))>0) { 

       myOutput.write(buffer, 0, len); 

      } 
      // Close the streams 
      myOutput.flush(); 
      myOutput.close(); 
      myInput.close(); 

     } 

请帮助我,并建议我需要改变。

回答

0

下面是如何可以将数据库轻松保存到SD卡:

private void backup() throws IOException { 
     File currentFile = new File(Environment.getDataDirectory(), "//data//" + activity.getPackageName() + "//databases//" + DATABASE_NAME); 

     File backupFile = new File(Environment.getExternalStorageDirectory(), DatabaseHandler.DATABASE_NAME); 
     backupFile.delete(); 
     backupFile.createNewFile(); 

     FileInputStream fis = new FileInputStream(currentFile); 
     FileOutputStream fos = new FileOutputStream(backupFile); 

     ByteStreams.copy(fis, fos); 

     fis.close(); 
     fos.close(); 
    } 

请注意,我用的字节流番石榴。

+0

不工作:(。有没有其他的解决方案?> – bibox

+0

为什么它不工作?究竟发生了什么? – SirGregg