我通过此代码获取我的数据库文件
File dbFile=getDatabasePath("EdsysEyfsDB.db"); Log.v("database name checking",dbFile.toString());
我想把这个数据库文件复制到sdcard中,所以我可以为此做一些操作.但是我不能做任何操作.以下代码用于复制到SD卡
if (dbFile.exists()) { InputStream inStream = new FileInputStream(dbFile); String file = Environment.getExternalStorageDirectory().getPath() +"/" + "database.db"; Log.d("file name checking in dbFilecondition",file); FileOutputStream fs = new FileOutputStream(file); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer,byteread); } inStream.close(); fs.close(); }
解决方法
尝试这个希望,这有助于你
public void exportDatabse(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,src.size()); src.close(); dst.close(); } } } catch (Exception e) { } }
如何调用
exportDatabse("YourDBName");
注意 :
记住要添加写入外部存储的权限< uses-permission android:name =“android.permission.WRITE_EXTERNAL_STORAGE”/>否则sd.canWrite()将为false.