【发布时间】:2018-10-03 07:41:49
【问题描述】:
我找到了一个可爱的功能,可以将我的数据库文件从原始路径复制到外部存储卡:
public static void copyFile(File src, File dst) throws IOException {
if(!dst.exists()) {
dst.createNewFile();
}
else{
dst.delete();
dst.createNewFile();
}
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
但我无法调用该函数,这里是我的代码在一个简单的按钮上:
exportDatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(Info.this, getDatabasePath(Info.this, "Library.sqlite"), Toast.LENGTH_SHORT).show();
File srcFile = new File(getDatabasePath(Info.this, "Library.sqlite"));
File dstFile = new File((getExternalStorageDirectory() + "/Library.sqlite"));
copyFile(srcFile, dstFile);
}
});
这行代码copyFile(srcFile, dstFile); 被标记为错误。在鼠标悬停时,我收到 Unhandled Exeption:java.IO.IOExeption
如何正确调用?
编辑: 补全缺失的代码,这里是按钮中用到的函数:
public String getDatabasePath(Context context,String databaseName)
{
return context.getDatabasePath(databaseName).getAbsolutePath();
}
public String getExternalStorageDirectory() {
String externalStorageDirectory;
externalStorageDirectory = Environment.getExternalStorageDirectory().toString();
return externalStorageDirectory;
}
我刚刚在 Memu(android 模拟器)中测试了我的解决方案,并且代码非常棒!我现在能够备份和恢复我的 SQLite 数据库。 (恢复简单的反转 dst 和 src 文件路径)。希望这会有所帮助。谢谢大家。
【问题讨论】: