Files copied by my app not showing up on PC

陌路散爱 提交于 2019-12-12 02:37:49

问题


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...

Here is the code I'm running to copy it:

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

}
//...

And here what FileUtil.copyFile function looks like:

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;

}

The code works on both devices we tested but none shows the file on the PC.

What I'm missing?


回答1:


As pointed out in the question linked by @CommonsWare, I made a little research about MediaScannerConnection class and it solved the problem.

Here is the final code:

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


来源:https://stackoverflow.com/questions/37946892/files-copied-by-my-app-not-showing-up-on-pc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!