我的应用程序复制的文件未显示在PC上

时间:2016-06-21 14:15:17

标签: java android file file-copying

我尝试在我的应用程序中运行简单的数据库备份,但是当我将设备连接到PC时文件没有显示,但在Android文件管理器中似乎没问题。该文件正被复制到" Downloads"顺便说一句文件夹...

以下是我要复制的代码:

//...
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上显示该文件。

我失踪了什么?

1 个答案:

答案 0 :(得分:0)

正如@CommonsWare链接的问题所指出的,我对MediaScannerConnection类进行了一些研究,它解决了这个问题。

以下是最终代码:

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
);