我刚用
写了一个文件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
会删除文件内容?
编辑:我添加了更详细的代码。我无法发布所有内容。这是一个很长的代码。主要的想法是:一切都很好。正确写入文件的数据。当我添加一个需要从文件中读取的新函数时,我收到了错误。在上面的代码中,我在编译器给出错误的行中添加了**注释。
答案 0 :(得分:1)
我认为你需要关闭你的BufferedWriter。然后,您可以阅读该文件,您将获得您的书面内容。作者的一个例子是here
答案 1 :(得分:0)
如果您想使用库而不是自己编写代码,请查看Apache Commons IO http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html中的FileUtils类)
经过试用和测试