我正在尝试导入一个sqlite数据库,以使其覆盖当前的数据库。我已经设法将数据库导出到电话上的文件夹中的文件中,但是当我尝试导入数据库时,出现了异常提示“没有这样的文件或目录”。我该如何解决?
这是我的数据库导出到文件的代码
private void exportDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath= "//data//" + "com.varcon.campus"
+ "//databases//" + "CampusTime.db";
String backupDBPath = "/Download/CampusTime";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
}
文件已成功导出到具有其名称的文件夹这是我导入数据库的代码
int PICKFILE_RESULT_CODE = 1;
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(chooseFile, PICKFILE_RESULT_CODE);
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent datas) {
Uri uri = datas.getData();
String filePath = uri.getPath();
try {
//Toast.makeText(this, ""+src, Toast.LENGTH_LONG).show();
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath= "//data//" + "com.varcon.campus"
+ "//databases//" + "CampusTime.db";
String backupDBPath = filePath;
File backupDB= new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
//new CustomMessage(getActivity(), "Database replaced sucessfully");
} catch (Exception e) {
e.printStackTrace();
//CustomLog.showLogD("WORKING_STOP",e.getMessage());
}
super.onActivityResult(requestCode, resultCode, datas);
}
而且我在清单中有权限
Stacktrace:
2020-03-10 23:14:43.704 31088-31088/com.varcon.campus D/error: java.io.FileNotFoundException: /storage/emulated/0/Download/CampusTime (No such file or directory)
唯一要做的就是为所选的uri打开InputStream,而不是对文件使用FileInputStream。
InputStream is = getContentResolver().openInputStream(data.getData());
然后照常从流中读取。