FileReader生成NPE

时间:2015-01-16 00:52:21

标签: java android java-io

我有一个本地存储在我的设备上的文件,如果我不重新启动手机,我会完全正常阅读。当我重新启动并读取日志时,新的FileReader会抛出一个NPE;为什么呢?

BufferedReader br = null;
FileReader fr = null;
    try {
        Log.d("DEBUG", "Before filereader");
        fr = new FileReader(ABS_FILENAME);
        Log.d("DEBUG", "Before BufferedReader");
        br = new BufferedReader(fr);

        String current;

        Log.d("DEBUG", "About to read file");
        while((current = br.readLine()) != null) {

        }
    }
    } catch (Exception e) {
        Log.d("DEBUG", "Exception thrown: " + e.getMessage());
    } finally {
        try {
            if (fr != null) {
                fr.close();
            }
        } catch (IOException ex) {
            Log.d("DEBUG", "Problem closing file reader");
        }
    }
    return null;

上述代码发生在广播接收器中。 ABS_FILENAME是表示文件的字符串。一旦点击某个内容,该文件就会定期写入活动中:

// in an onClick that gets invoked
try {
            String line = myKey + " " + myValue;
            fw.write(line);
            fw.write(System.getProperty("line.separator"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fw != null)
                    fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

// elsewhere in the activity
@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    myFile = new File(getFilesDir(), FILENAME);
    try {
        if (!myFile.exists()) {
            myFile.createNewFile();
        }
        ABS_FILENAME = myFile.getAbsolutePath();
        fw = new FileWriter(myFile.getAbsoluteFile(), true);
    } catch(IOException e) {
    }

1 个答案:

答案 0 :(得分:0)

如果

new FileReader(ABS_FILENAME)

确实产生NullPointerException, ABS_FILENAME必须为空。