我刚刚写了一个文件使用
FileWriter fWrite=new FileWriter("C:/folder/DP.txt");
BufferedWriter output = new BufferedWriter(fWrite);
int lastItem = splitItems(capacity); //** calling the function that returns the last item in the file
output.close();
然后我关闭了文件并确保数据已写入。在另一个函数中,我需要读取我刚刚编写的数据。我写了以下代码:
public static int splitItems(int capacity) throws IOException //read items from the file
{
BufferedReader br = new BufferedReader(new FileReader("C:/folder/DP.txt"));
//read the last line from file
String tmp, strLine = null;
while ((tmp = br.readLine()) != null)
{
strLine = tmp;
} //end while
String lastLine = strLine; //save the last line
String[] split = lastLine.split("\\s+"); /** split based on spaces
int lastItem=Integer.parseInt(split[capacity]); //save the int in the file
br.close(); //closing the file
return lastItem; //return the last number
}//end split items
然后,在运行中,我收到以下错误:
java.lang.NullPointerException
当我检查文件时,我发现它是空的。问题是什么。为什么要BufferedReader
删除文件内容?
编辑:我添加了更详细的代码。我不能全部发布。这是相当长的代码。主要思想是:一切都很好。正确写入文件的数据。当我添加一个需要从文件中读取的新函数时,我得到了错误。在上面的代码中,我在编译器给出错误的行中添加了一个 ** 注释。