gpt4 book ai didi

java - 使用 Java 方法更新文本文件上的单行

转载 作者:行者123 更新时间:2023-12-01 11:47:20 25 4
gpt4 key购买 nike

我知道以前有人问过像这样的问题,但这个问题与我编写的代码的细节有关。我正在尝试更新文件上的一行代码,即使程序终止,该文件也会永久更新,以便可以再次调出数据。我目前正在编写的方法如下所示(使用 eclipse 未发现编译错误)

public static void editLine(String fileName, String name, int element,
String content) throws IOException {
try {
// Open the file specified in the fileName parameter.
FileInputStream fStream = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
fStream));
String strLine;
StringBuilder fileContent = new StringBuilder();

// Read line by line.
while ((strLine = br.readLine()) != null) {
String tokens[] = strLine.split(" ");
if (tokens.length > 0) {
if (tokens[0].equals(name)) {
tokens[element] = content;
String newLine = tokens[0] + " " + tokens[1] + " "
+ tokens[2];
fileContent.append(newLine);
fileContent.append("\n");
} else {
fileContent.append(strLine);
fileContent.append("\n");
}
}

/*
* File Content now has updated content to be used to override
* content of the text file
*/
FileWriter fStreamWrite = new FileWriter(fileName);
BufferedWriter out = new BufferedWriter(fStreamWrite);
out.write(fileContent.toString());
out.close();

// Close InputStream.
br.close();
}
} catch (IOException e) {
System.out.println("COULD NOT UPDATE FILE!");
System.exit(0);
}
}

如果您可以查看代码并让我知道您的建议,那就太好了,因为目前我只收到捕获消息。

最佳答案

好的。首先,StringBuilder fileContent = new StringBuilder(); 是不好的做法,因为该文件很可能大于用户的可用内存。您根本不应该将文件的大部分内容保留在内存中。通过读入缓冲区、处理缓冲区(如有必要进行调整)并将缓冲区写入新文件来完成此操作。完成后,删除旧文件并将辅助文件重命名为旧文件的名称。希望这会有所帮助。

关于java - 使用 Java 方法更新文本文件上的单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29054921/

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