在我的Android应用程序中读写文件

时间:2014-10-20 16:50:35

标签: android android-permissions

我在google和stackoverflow中长时间搜索后发布此内容。

我试图在我的应用程序中读/写一个文件,我使用以下代码来做同样的事情:

public class FileOperations {
 public FileOperations() {
  }
public Boolean write(String fname, String fcontent){
  try {
    String fpath = Environment.getExternalStorageDirectory().getPath() +fname+".txt";
    File file = new File(fpath);
    // If file does not exists, then create it
    if (!file.exists()) {
      file.createNewFile();
    }
    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(fcontent);
    bw.close();
    Log.d("Suceess","Sucess");
    return true;
  } catch (IOException e) {
    e.printStackTrace();
    return false;
  }
}
public String read(String fname){
 BufferedReader br = null;
 String response = null;
  try {
    StringBuffer output = new StringBuffer();
    String fpath = Environment.getExternalStorageDirectory().getPath() +fname+".txt";
    br = new BufferedReader(new FileReader(fpath));
    String line = "";
    while ((line = br.readLine()) != null) {
      output.append(line +"\n");
    }
    response = output.toString();
  } catch (IOException e) {
    e.printStackTrace();
    return null;
  }
  return response;
 }
}

我已添加以下权限:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

我收到以下错误:

10-20 22:09:54.101: W/System.err(11634): java.io.IOException: open failed: EACCES (Permission denied)
10-20 22:09:54.101: W/System.err(11634):    at java.io.File.createNewFile(File.java:946)

1 个答案:

答案 0 :(得分:0)

谢谢。 @Chris Stratton 正如你所提到的,我将我的文件名改为&#34; /&#34; + filename并且它有效。