我的应用程序复制的文件未显示在PC上 [英] Files copied by my app not showing up on PC
问题描述
我正在尝试在应用程序中运行简单的数据库备份,但是当我将设备连接到PC时文件没有显示,但是在Android File Manager中似乎可以.该文件正在通过以下方式复制到下载"文件夹中...
I'm trying to run a simple database backup in my application, but the files are not showing up when I connect the device to my PC, but appears to be OK in the Android File Manager. The file is being copied to "Downloads" folder by the way...
这是我要复制的代码:
//...
private void backupDatabase(){
String downloadsPath = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath();
String backupDirectoryPath = downloadsPath+"/myapp_backups/";
File backupDirectory = new File(backupDirectoryPath);
backupDirectory.mkdirs();
String bkpFileName = "backup_"+(new Date().getTime())+".bkp";
String src = mContext.getDatabasePath(DatabaseHelper.DATABASE_NAME).getAbsolutePath();
String dest = backupDirectoryPath + bkpFileName;
FileUtil.copyFile(src, dest);
}
//...
这是 FileUtil.copyFile
函数的样子:
public static boolean copyFile(String src, String dest){
boolean success;
try{
if(!isFile(src)){
throw new Exception("Source file doesn't exist: "+src);
}
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
// 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();
success = true;
}catch (Exception exception){
exception.printStackTrace();
success = false;
}
return success;
}
该代码在我们测试过的两种设备上均有效,但都无法在PC上显示该文件.
The code works on both devices we tested but none shows the file on the PC.
我想念什么?
推荐答案
正如@CommonsWare链接的问题所指出的那样,我对 MediaScannerConnection
类进行了一些研究,并解决了该问题.
As pointed out in the question linked by @CommonsWare, I made a little research about MediaScannerConnection
class and it solved the problem.
这是最终代码:
String downloadsPath = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath();
String backupDirectoryPath = downloadsPath+"/myapp_backups/";
File backupDirectory = new File(backupDirectoryPath);
backupDirectory.mkdirs();
String bkpFileName = "backup_"+(new Date().getTime())+".bkp";
String src = mContext.getDatabasePath(DatabaseHelper.DATABASE_NAME).getAbsolutePath();
String dest = backupDirectoryPath + bkpFileName;
FileUtil.copyFile(src, dest);
//Scan the new file, so it will show up in the PC file explorer:
MediaScannerConnection.scanFile(
mContext, new String[]{dest}, null, null
);
这篇关于我的应用程序复制的文件未显示在PC上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!