读取和写入y android应用程序中的文件

问题描述:

我在谷歌和stackoverflow长搜索后发布这个。读取和写入y android应用程序中的文件

我试图读/写在我的应用程序的文件,我用下面的代码做相同的:

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) 
+0

您只需要其中一个权限,因为写意味着读取。但是你可能把它们放在清单中的错误位置。它也看起来像你可能会缺少一个路径分隔符 - 注销你试图访问的路径。 – 2014-10-20 16:56:42

谢谢。 @Chris Stratton 正如你所提到的,我将我的文件名改为“/”+文件名,它工作。