2014-09-22 103 views
0

我试图在Android 4.4.4版本中运行Moto G中的文件写入操作。 我在清单中添加了文件写入权限文件也是。但是文件写入仍然以各种可能的方式失败。在android中使用java.io.IOException的文件写入失败:打开失败:EACCES(权限被拒绝)

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

<使用权限android:name =“android.permission.WRITE_EXTERNAL_STORAGE”/>在mainfest中 – sunil 2014-09-22 13:07:29

+0

在您的应用程序中添加''“”“标签 – 2014-09-22 13:07:32

+0

我在清单中添加了以下权限。 <使用权限android:name =“android.permission.READ_EXTERNAL_STORAGE”/> <使用权限android:name =“android.permission.MOUNT_UNMOUNT_FILESYSTEMS”/> 但是没有运气... – kabilan 2014-09-22 13:20:28

回答

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; 
} 

,并尝试这个 链接http://developer.android.com/reference/android/content/Context.html#getDir%28java.lang.String,%20int%29

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

+0

moto g没有外部存储,所以尽量写在内部存储空间,请张贴您的mainfest – sunil 2014-09-22 14:06:01

+0

大家好,我解决了这个问题。我忘了在application_to_test清单中添加写权限。一旦添加,问题就消失了。感谢您的所有提示。 – kabilan 2014-09-23 06:48:59

相关问题