gpt4 book ai didi

java - 如何在 Java 中删除文本文件的最后一行?

转载 作者:太空宇宙 更新时间:2023-11-04 11:39:11 25 4
gpt4 key购买 nike

我有一个包含一些字符串的文件。例如:

迈克1111
克里斯2222
布莱恩3333

我正在尝试编写代码来从该文件中删除一行。但是,例如,当我删除 Chris 时,它会变成:

迈克1111
布莱恩3333
(空行)

空行是一个问题,因为当我添加另一个字符串时,它将出现在空行之后而不是在它的位置。先感谢您。这是我的代码:

public void deleteUser(String u, String p) throws IOException {
username = u;
pin = p;

File userAccountFolder = new File("userLogin.txt");
File temporaryFile = new File("temporaryFile.txt");

BufferedReader buffReader = new BufferedReader(new FileReader(userAccountFolder));
BufferedWriter buffWriter = new BufferedWriter(new FileWriter(temporaryFile));

String lineToRemoveFromFile = username + pin;
String lineFromUserFile;

while ((lineFromUserFile = buffReader.readLine()) != null) {

String trimmedLine = lineFromUserFile.trim();
if (trimmedLine.equals(lineToRemoveFromFile)) {
continue;
}

buffWriter.append(lineFromUserFile + System.getProperty("line.separator"));
}
buffWriter.close();
buffReader.close();

boolean removed = temporaryFile.renameTo(userAccountFolder);
if (removed == true) {
System.out.println(username + "'s account has been removed.");

}

}

最佳答案

这可以解决问题,添加一个 boolean 检查。

        BufferedReader buffReader = new BufferedReader(new FileReader(userAccountFolder));
BufferedWriter buffWriter = new BufferedWriter(new FileWriter(temporaryFile));

String lineToRemoveFromFile = username + pin;
String lineFromUserFile;

boolean addnewLine = false;

while ((lineFromUserFile = buffReader.readLine()) != null) {

String trimmedLine = lineFromUserFile.trim();
if (trimmedLine.equals(lineToRemoveFromFile)) {
continue;
}

if (addnewLine) {
buffWriter.newLine();
} else {
addnewLine = true;
}
buffWriter.append(lineFromUserFile);

}
buffWriter.close();
buffReader.close();

关于java - 如何在 Java 中删除文本文件的最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42966607/

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