我有下一个问题......我在源头搜索了答案,但没有找到一个好的答案......
java.io.FileNotFoundException: /mounted/EmailClient/side-corner.png: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:453)
at java.io.FileOutputStream.<init>(FileOutputStream.
at java.io.FileOutputStream.<init>(FileOutputStream.java:73) etc
代码:
private static String saveFile(String filename, InputStream input) {
String path = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(path)) {
try {
byte[] attachment = new byte[input.available()];
input.read(attachment);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/EmailClient/", filename);
if (!file.mkdirs())
Log.d("EmailClient", "saveFile: Dir not created");
FileOutputStream out = new FileOutputStream(file); //PROBLEM!
out.write(attachment);
input.close();
out.close();
return path;
} catch (IOException e) {
Log.e("EmailClient", "saveFile: File not saved", e);;
}
}
return path;
}
答案 0 :(得分:3)
使用此代码
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/EmailClient/");
folder.mkdirs();
File file = new File(folder,filename);
file.createNewFile();
答案 1 :(得分:1)
我认为您正在尝试将文件保存在&#34; DIRECTORY_DOWNLOADS&#34;目录,。所以你应该按照下面的代码。 下面的行给出了目录。
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
如果您想创建特定文件夹&#34; Email_Client&#34;在该路径内,写下这一行。
File folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+"/Email_Client/");
你应该宣布许可&#34; WRITE_EXTERNAL_STORAGE&#34;
String fileName="myfile.txt";
String input="Hello World";
String path = Environment.getExternalStorageState();
File file=null;
if (Environment.MEDIA_MOUNTED.equals(path)) {
try {
byte[] attachment = input.getBytes();
File folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+"/Email_Client/");
folder.mkdirs();
file=new File(folder,fileName);
//Automatically creates the new empty file specified by the name, if it is not exist.
file.createNewFile();
Log.i("EmailClient", "saveFile: Dir created");
FileOutputStream out = new FileOutputStream(file);
out.write(attachment);
out.close();
} catch (IOException e) {
Log.e("EmailClient", "saveFile: File not saved", e);;
}
}
答案 2 :(得分:1)
如果您正在构建目标版本 API 级别高于 27 的应用,则默认情况下禁用存储访问。如果您想快速启用它,请在您的 AndroidManifest.xml
文件中添加以下行。
<manifest ... >
<application
android:requestLegacyExternalStorage="true" //add this line
... >
...
</application>
</manifest>