我正在使用这种方法将我的db文件复制到sd car请告诉我sd卡上的文件是否已经存在然后是否会替换或不会复制?
public boolean copyDbToSDCard() {
boolean success = false;
String SDCardPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
final String DBPATH = SDCardPath + "/BD/";
final String DBNAME = "Mydb3.db";
this.getReadableDatabase();
File directory = new File(DBPATH);
if (!directory.exists())
directory.mkdir();
close();
try {
InputStream mInput = new FileInputStream(DB_PATH + DB_NAME);
OutputStream mOutput = new FileOutputStream(DBPATH + DBNAME);
byte[] buffer = new byte[1024];
int length;
while ((length = mInput.read(buffer)) > 0) {
mOutput.write(buffer, 0, length);
}
mOutput.flush();
mOutput.close();
mInput.close();
success = true;
} catch (Exception e) {
Toast.makeText(myContext,
"copyDbToSDCard Error : " + e.getMessage(),
Toast.LENGTH_SHORT).show();
e.fillInStackTrace();
}
return success;
}
答案 0 :(得分:1)
您可以检查数据库是否可用?
像这样checkDB()
{
try{
SQLiteDatabase dbe = SQLiteDatabase.openDatabase("selectedFilePath", null,0);
Log.d("opendb","EXIST");
dbe.close();
// DB exits then delete
File file = new File(selectedFilePath);
boolean deleted = file.delete(); <--- this will help you to delete DB
}
catch(Exception e)
{
// DB not exits code to copy database
}
}
答案 1 :(得分:1)
代码:
OutputStream mOutput = new FileOutputStream(DBPATH + DBNAME);
和
mOutput.write(buffer, 0, length);
表示如果文件存在,它将用新数据
替换文件的内容