从 mkdir() 创建文件失败

Create file failed from mkdir()

我尝试在我的 android 模拟器中创建文件,但是当我完成我的代码时。 我找不到我从 android 设备监视器创建的文件。

这是我的代码:

try {
    if (Environment.getExternalStorageState()
            .equals(Environment.MEDIA_MOUNTED)) {
        System.out.println("can be read and write");
        File sdFile = android.os.Environment.getExternalStorageDirectory();

        //String path = sdFile.getPath() + File.separator + "DestPdf";
        String path = sdFile.getPath() + "/demos/file/tmp/test";
        File dirFile = new File(path);

        if (!dirFile.exists()) { // if file doesn't exist
            System.out.println("create file");
            dirFile.mkdir(); // create file
            System.out.println(dirFile.toString());
        }
    }
} catch (Exception ex) {
    ex.toString();
}

我还添加了一些权限:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

这是我的打印输出,我可以看到根 /storage/sdcard/demos/file/tmp/test

11-17 08:38:10.263 15501-15501/? I/System.out: can be read and write
11-17 08:38:10.263 15501-15501/? I/System.out: create file
11-17 08:38:10.264 15501-15501/? I/System.out: /storage/sdcard/demos/file/tmp/test

但我无法从 android 设备监视器中找到该文件

我错过了哪一步?任何帮助,将不胜感激 。提前致谢。

你应该替换

dirFile.mkdir();

dirFile.mkdirs();

示例:

if (!dirFile.exists()) { // if file doesn't exist
        System.out.println(dirFile.mkdir());
        System.out.println(dirFile.mkdirs());

    }

第一个会产生 false [并且不会创建任何目录],第二个会产生 true,并且您将创建 /demos/file/tmp/test

mkdirs() 还会在此文件所代表的路径中创建父目录。

mkdirs() 的 javadocs:

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

mkdir() 的 javadocs:

Creates the directory named by this abstract pathname.

希望能帮到你!

几个月前我遇到了同样的问题。

在我的例子中,文件在那里,但 windows 看不到它(或者 adb 和 windows 资源管理器之间的集成)。

重置 MOBILE 是我找到的唯一解决方案...重置后文件在 Windows Explorer 中。

我建议您尝试使用 cli 命令查找您的文件:

adb shell ls sdcard/"your_path"                                                                                           

此外,尝试使用以下方法创建它:

.getAbsolutePath()

像这样:

File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "YOUR_FOLDER_NAME");

if(!path.exists()) 
{
    path.mkdirs();
} 
else 
{ 
    Log.d ("TAG","Path already exists");
}

希望对您有所帮助

对于 Android 6+,您需要添加代码以要求用户确认您在清单中请求的权限。

Google 运行时权限。