问题描述
我们试图通过获取路径,创建新目录,然后在该目录中创建文件来在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;
}