簡體   English   中英

在Android中使用java.io.IOException寫入文件失敗:打開失敗:EACCES(權限被拒絕)

[英]File write failed in android with java.io.IOException: open failed: EACCES (Permission denied)

我試圖在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();
            }
            }

請幫我解決這個問題。 我嘗試了所有可能的方式。 但是找不到解決方案。

 //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#files內部

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM