java.io.FileNotFoundException在外部存储中打开失败的ENOENT

时间:2016-08-19 13:11:22

标签: java android filenotfoundexception

所以我在网上关注了这个例外的一些建议,包括:

  • 不直接在外部根目录下创建文件 存储;
  • 向清单添加写入和读取权限;
  • 将我的数字文件名更改为非数字。
  • 阅读时的用户FileInputStream。

但是我仍然看到抛出此异常:

  

java.io.FileNotFoundException,打开失败:ENOENT

这是我的班级:

public class SaveReminderToFile {
    private String fileName;
    private File gFile;

    public SaveReminderToFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException {
        this.fileName = "reminder"+fileName+".txt";
        File root = android.os.Environment.getExternalStorageDirectory();

        File dir = new File(root.getAbsolutePath()+"/ReminderApp2");
        if (!dir.exists()){
            dir.mkdirs();//create folders where write files
        }
         gFile = new File(dir,this.fileName);
    }

    public void writeToFile(String[] data, Context context){
        try{

            BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(gFile.getAbsoluteFile()), "UTF-8"));
            for(String word :data) {
                oFile.write(word);
                oFile.newLine();
            }
            oFile.close();
        }catch(IOException e){
            Log.e("Exception",e.getMessage());
        }
    }

  public String readFromFile(){
        String ret="";
        try{
            FileInputStream inputStream =new FileInputStream(gFile.getAbsolutePath()); 
            if ( inputStream != null ) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(receiveString);
                }

                inputStream.close();
                ret = stringBuilder.toString();
            }
        } catch (FileNotFoundException e) {

            Log.e("login activity", "File not found: " + e.toString());
            ret=e.toString();
        } catch (IOException e) {
            Log.e("login activity", "Can not read file: " + e.toString());
            ret=e.toString();
        }
        return ret;
    }
    }

0 个答案:

没有答案