我正在尝试在Moto G中运行的android 4.4.4版本中执行文件写入操作。 我也在清单文件中添加了文件写入权限。但是文件写入会以各种可能的方式继续失败。
java.io.IOException: open failed: EACCES (Permission denied)
这是我收到的错误消息。我的代码在下面,
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/text.txt");
if (!file.exists()) {
try {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("hi");
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
请帮我解决这个问题。我试着用各种可能的方式。但无法找到解决方案。
答案 0 :(得分:0)
//check if external storage is available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into
使用内部存储
链接http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
链接: http://www.mysamplecode.com/2012/06/android-internal-external-storage.html