2011-10-12 67 views
1

我的Android手机上有一个数据库,我需要将这些信息放到SD卡上。是否可以将数据库文件复制到SD卡?

是否可以将数据库文件以可读状态保存到SD卡上?我一直无法找到关于如何做到这一点的任何信息。

将数据库文件复制到SD卡的一些源代码将是理想的。

+0

安装ADK并使用adb移动/拉动它? – Rob

+0

感谢您输入Rob。但是,这将需要在电话上的Root权限,我需要远离。否则,这将是一个完美的解决方案。 – Dave

回答

0

这是我从SO上的其他几个用户混蛋的脚本。看起来你可以告诉android在哪里存储文件,但是当你用adb shell进入手机时,你可能很难找到它!

此代码(我将其映射到我的操作栏中用于调试的临时按钮)会打印出如下内容:“数据库已保存到:/ storage/emulated/0/DB-DEBUG/todotable.db”,但将进入在我的手机上的外壳我实际上发现我的数据库在:“/ storage/emulated/legacy/DB-DEBUG /”......不知道这是怎么回事,但现在我可以用sqlite浏览器检查我的数据库!

//db will reside in: /storage/emulated/legacy/DB_DEBUG 
private void copyDatabase(Context c, String DATABASE_NAME) { 
    String databasePath = c.getDatabasePath(DATABASE_NAME).getPath(); 
    File f = new File(databasePath); 
    OutputStream myOutput = null; 
    InputStream myInput = null; 
    Log.d("testing", " testing db path " + databasePath); 
    Log.d("testing", " testing db exist " + f.exists()); 

    if (f.exists()) { 
     try { 
      File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DB-DEBUG"); 
      if (!directory.exists()){ 
       directory.mkdir(); 
      } 

      String copyPath = directory.getAbsolutePath() + "/" + DATABASE_NAME; 
      myOutput = new FileOutputStream(copyPath); 
      myInput = new FileInputStream(databasePath); 

      byte[] buffer = new byte[1024]; 
      int length; 
      while ((length = myInput.read(buffer)) > 0) { 
       myOutput.write(buffer, 0, length); 
      } 

      myOutput.flush(); 
      Toast.makeText(getBaseContext(), "Your database copied to: " + copyPath, Toast.LENGTH_LONG).show(); 
      Log.d("testing", " database saved to: " + copyPath); 

     } catch (Exception e) { 
      Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); 

     } finally { 
      try { 
       if (myOutput != null) { 
        myOutput.close(); 
        myOutput = null; 
       } 
       if (myInput != null) { 
        myInput.close(); 
        myInput = null; 
       } 
      } catch (Exception e) { 
       Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 
} 
相关问题