尝试保存文件时找不到文件
FileNotFound when tring to save file
我有一个奇怪的问题。我正在尝试保存我的 sqlite 数据库的备份。我创建了这段代码
String DB_PATH;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
DB_PATH = context.getFilesDir().getAbsolutePath().replace("files", "databases") + File.separator;
}
else {
DB_PATH = context.getFilesDir().getPath() + context.getPackageName() + "/databases/";
}
String currentDBPath = "portals.db";
String backupDBPath = "backupname.db";
File sd = new File(Environment.DIRECTORY_DOWNLOADS + "/" + backupDBPath);
File data = new File(DB_PATH + currentDBPath);
try {
InputStream in = new FileInputStream(data);
OutputStream out = new FileOutputStream(sd);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch(Exception e) {
int test = 1;
e.printStackTrace();
}
当我 运行 收到 FileNotFound 异常时。它不应该创建文件吗?我什至尝试创建一个虚拟文件,结果仍然相同。
请注意,我想将其保存在内部存储器中,因为我的设备中没有 SD 卡。该代码有什么问题?
我找到了解决办法。
用我的代码行解决问题
File sd = new File(Environment.DIRECTORY_DOWNLOADS + "/" + backupDBPath);
应该是这样的
File sd = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOCUMENTS + "/" + backupDBPath);
未来也很有趣。该文件已正确保存,但我只能在拔下并插入设备后才能看到它。因此,就与 pc
的连接而言,需要某种重启
我有一个奇怪的问题。我正在尝试保存我的 sqlite 数据库的备份。我创建了这段代码
String DB_PATH;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
DB_PATH = context.getFilesDir().getAbsolutePath().replace("files", "databases") + File.separator;
}
else {
DB_PATH = context.getFilesDir().getPath() + context.getPackageName() + "/databases/";
}
String currentDBPath = "portals.db";
String backupDBPath = "backupname.db";
File sd = new File(Environment.DIRECTORY_DOWNLOADS + "/" + backupDBPath);
File data = new File(DB_PATH + currentDBPath);
try {
InputStream in = new FileInputStream(data);
OutputStream out = new FileOutputStream(sd);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch(Exception e) {
int test = 1;
e.printStackTrace();
}
当我 运行 收到 FileNotFound 异常时。它不应该创建文件吗?我什至尝试创建一个虚拟文件,结果仍然相同。
请注意,我想将其保存在内部存储器中,因为我的设备中没有 SD 卡。该代码有什么问题?
我找到了解决办法。
用我的代码行解决问题
File sd = new File(Environment.DIRECTORY_DOWNLOADS + "/" + backupDBPath);
应该是这样的
File sd = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOCUMENTS + "/" + backupDBPath);
未来也很有趣。该文件已正确保存,但我只能在拔下并插入设备后才能看到它。因此,就与 pc
的连接而言,需要某种重启