在android / java中调用createNewFile时,为什么会得到:java.io.IOException:没有这样的文件或目录

问题描述

我们试图通过获取路径,创建新目录,然后在该目录中创建文件来在android中创建文件,但是在运行时出现错误。 这是代码:

private File createTestFile() throws IOException {
    String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/RNDAlexaData/";
    Log.d("rootpath",rootPath);
    File root = new File(rootPath);
    if (!root.exists()) {
        root.mkdirs();
    }
    File f = new File(rootPath + "test.pcm");
    if (f.exists()) {
        f.delete();
    }
    f.createNewFile();
  
    FileOutputStream out = new FileOutputStream(f);

    out.flush();
    out.close();

    return f;
}

android的输出:

D/rootpath: /storage/emulated/0/RNDAlexaData/
D/Response error: java.io.IOException: No such file or directory
W/System.err: java.io.IOException: No such file or directory
        at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
        at java.io.File.createNewFile(File.java:1008)
        at aut.rnd.alexa.ui.account.AccountFragment$TokenListener.createTestFile(AccountFragment.java:318)

Android清单具有以下权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

解决方法

在评论中使用谷歌搜索和@blackapps和@Andreas解决了我自己的问题。

Environment.getExternalStorageDirectory()已过时,请改用mContext.getExternalFilesDir(null).getAbsolutePath()

private File createTestFile() throws IOException {
    File dataFolder = new File(mContext.getExternalFilesDir(null).getAbsolutePath(),"RNDAlexaData");
    Log.d("parent",dataFolder.getParent());

    if (!dataFolder.exists()) {
        Log.d("mkdir_success","Succesfully created directory: " + dataFolder.mkdirs());
    }
    else {
        Log.d("fileexists","true");
    }

    File testMediaFile = new File(dataFolder,"test.pcm");
    if (testMediaFile.exists()) {
        testMediaFile.delete();
    }
    Log.d("media_file","successfully created: " + testMediaFile.createNewFile());

    FileOutputStream out = new FileOutputStream(testMediaFile);
    // TODO
    out.flush();
    out.close();

    return testMediaFile;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...