0

我刚刚写了一个文件使用

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删除文件内容?

编辑:我添加了更详细的代码。我不能全部发布。这是相当长的代码。主要思想是:一切都很好。正确写入文件的数据。当我添加一个需要从文件中读取的新函数时,我得到了错误。在上面的代码中,我在编译器给出错误的行中添加了一个 ** 注释。

4

2 回答 2

1

我认为您需要关闭 BufferedWriter。然后你可以阅读文件,你会得到你的书面内容。作者的一个例子是here

于 2013-06-30T19:24:38.603 回答
0

如果您想使用库而不是自己编写代码,请查看 Apache Commons IO http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils 中的 FileUtils 类。 html )

久经考验

于 2013-06-30T19:30:35.707 回答