gpt4 book ai didi

java - 如何使用java从文本文件中删除一行?

转载 作者:行者123 更新时间:2023-11-29 04:59:37 25 4
gpt4 key购买 nike

在询问用户他/她想要删除的内容后,我想从文本文件中删除一行,但我不知道在我的代码中下一步该做什么。

文本文件如下所示:

1::name::mobileNum::homeNum::fax::birthday::email::website::address // line the user wants to delete
2::name::mobileNum::homeNum::fax::birthday::email::website::address
3::name::mobileNum::homeNum::fax::birthday::email::website::address

这是我的代码:

public static void readFromFile(String ans, String file) throws Exception {
BufferedReader fileIn = new BufferedReader(new FileReader(file));
GetUserInput console = new GetUserInput();

String checkLine = fileIn.readLine();

while(checkLine!=null) {
String [] splitDetails = checkLine.split("::");
Contact details = new Contact(splitDetails[0], splitDetails[1], splitDetails[2], splitDetails[3], splitDetails[4], splitDetails[5], splitDetails[6], splitDetails[7], splitDetails[8]);
checkLine = fileIn.readLine();


if(ans.equals(splitDetails[0])) {
// not sure what the code will look like here.
// in this part, it should delete the line the user wants to delete in the textfile

}
}
}

所以文本文件的输出应该是这样的:

2::name::mobileNum::homeNum::fax::birthday::email::website::address
3::name::mobileNum::homeNum::fax::birthday::email::website::address

另外,我想将第2行和第3行调整为第1行和第2行:

1::name::mobileNum::homeNum::fax::birthday::email::website::address
2::name::mobileNum::homeNum::fax::birthday::email::website::address

我该怎么做?

最佳答案

这是一个工作代码,假设您使用的是 Java >= 7:

public static void removeLine(String ans, String file) throws IOException {
boolean foundLine = false;
try (BufferedReader br = Files.newBufferedReader(Paths.get(file));
BufferedWriter bw = Files.newBufferedWriter(Paths.get(file + ".tmp"))) {
String line;
while ((line = br.readLine()) != null) {
String[] tokens = line.split("::", 2);
if (tokens[0].equals(ans)) {
foundLine = true;
} else {
if (foundLine) {
bw.write((Integer.parseInt(tokens[0]) - 1) + "::" + tokens[1]);
} else {
bw.write(line);
}
bw.newLine();
}
}
}
Files.move(Paths.get(file + ".tmp"), Paths.get(file), StandardCopyOption.REPLACE_EXISTING);
}

无法从文件中删除一行。您需要做的是读取现有文件,将要保留的内容写入临时文件,然后重命名临时文件以覆盖输入文件。

此处,临时文件创建在与输入文件相同的目录中,并添加了扩展名 .tmp(请注意,您也可以为此使用 Files.createTempFile)。

对于读取的每一行,我们检查这是否是用户想要删除的行。

  • 如果是,我们更新一个 boolean 变量,告诉我们我们只是命中要删除的行,我们不会将此行复制到临时文件。
  • 如果不是,我们有一个选择:
    • 要么我们还没有到达要删除的行。然后我们简单的把读到的内容复制到临时文件中
    • 或者我们做了,我们需要减少第一个数字并将该行的其余部分复制到临时文件。

当前行在 String.split(regex, limit) 的帮助下被拆分(它只将该行拆分两次,从而创建一个包含 2 个字符串的数组:第一部分是数字,第二部分是该行的其余部分)。

最后,临时文件用Files.move覆盖了输入文件(我们需要使用 REPLACE_EXISTING 选项)。

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

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