java - 如何使用 Java 读取已写入的文件

标签 java

我刚刚使用写入文件

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

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

最佳答案

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

关于java - 如何使用 Java 读取已写入的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17394014/

相关文章:

java - Hibernate:如何映射到静态表?

java - 在java中继承后 protected 成员会发生什么?

java - 为什么 Java 的优先级队列缺少更改优先级的方法?

java - 泛型类型是什么意思?

java - 使用 java 使用 servlet 和 web 项目时出现问题

OpenWrt/DD-WRT 上的 Java

java - ConcurrentHashMap 上的竞争条件问题

java - NoNodeAvailableException[配置的节点均不可用 : [{#transport#-1}{. ..}{127.0.0.1}{127.0.0.1:9300}]]

java - 如何以编程方式设置编辑文本的可绘制背景

java - 对链接列表进行插入排序,数据来自文本文件。 java