![](/img/trans.png)
[英]File.createNewFile() gives java.io.IOException: Permission denied
[英]When calling createNewFile() in android/java, why do I get: java.io.IOException: No such file or directory
我們嘗試通過獲取路徑、創建新目錄然后在該目錄中創建文件來在 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;
}
Output 來自 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 Manifest 具有以下權限:
<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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.