如何解决在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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。