2014-10-20 55 views
0

我在谷歌和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

回答

0

謝謝。 @Chris Stratton 正如你所提到的,我將我的文件名改爲「/」+文件名,它工作。