gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:22:53 26 4
gpt4 key购买 nike

我刚刚使用写入文件

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com