File does exists when calling .exists() but can't find it later

不羁的心 提交于 2019-12-13 04:22:29

问题


I'm trying to create a file that is eventually going to hold a picture (EXTRA_OUTPUT) like this:

    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                      Environment.DIRECTORY_PICTURES), "scouthouse");
            if(!mediaStorageDir.exists()) {
                mediaStorageDir.mkdirs();
            }

            SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
            String format = s.format(new Date());
            File file = new File(mediaStorageDir.getPath() + File.separator + format + ".jpg");
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

The mediaStorageDir.exists() returns true, but I can't find the folder in windows. The location is sdcard0/Pictures/scouthouse/. I do have a Pictures/ folder but Android doesn't create the /scouthouse/ folder. When I try to decode the file with a Bitmapfactory it returns null.

EDIT!

So I've simplified the method a bit to get down to the root and basically have this:

   private void createDir() {
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "scouthouse");
    if(!file.mkdirs()) {
        Log.d("file", "file not created");
    }   
}

This creates a file dir, and the Log isn't logged for the first time. So the directory has been created, however I can't find it on the phones file system anywhere.

    private File createNewFile() {
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "scouthouse" + File.separator + "test.jpg");
    try {
        if(file.createNewFile()) {
            Log.d("file", "yiss");
            return file;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

This method returns null. The file can't be created..


回答1:


The mediaStorageDir.exists() returns true, but I can't find the folder in windows.

Probably that is because MediaStore does not know about the directory, and so the MTP connection to Windows does not know about the directory. You can try using MediaScannerConnection and scanFile() to resolve this, though I have only tried that for files, not directories. Also, even after indexing, you may need to do "Refresh" from your Explorer window, or disconnect/reconnect the device, as Windows may cache the MTP results and not detect a change even if Android knows about it.



来源:https://stackoverflow.com/questions/18593334/file-does-exists-when-calling-exists-but-cant-find-it-later

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