gpt4 book ai didi

Java 从文件中删除行

转载 作者:行者123 更新时间:2023-12-02 04:47:56 24 4
gpt4 key购买 nike

下面的代码来 self 在网上看到的引用,所以可能有一些相似之处,我正在尝试实现代码以根据第一个字段删除整行,在本例中它是(aaaa 或 bbbb)文件其中有一个分隔符“|”,但它不起作用。希望有人能就此给我建议。我需要先把线分开吗?还是我的方法不对?

player.dat 中的数据(例如)

bbbb|aaaaa|cccc
aaaa|bbbbbb|cccc

代码如下

public class testcode {

public static void main(String[] args)throws IOException
{
File inputFile = new File("players.dat");
File tempFile = new File ("temp.dat");

BufferedReader read = new BufferedReader(new FileReader(inputFile));
BufferedWriter write = new BufferedWriter(new FileWriter(tempFile));

Scanner UserInput = new Scanner(System.in);
System.out.println("Please Enter Username:");
String UserIn = UserInput.nextLine();

String lineToRemove = UserIn;
String currentLine;

while((currentLine = read.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
write.write(currentLine + System.getProperty("line.separator"));
}
write.close();
read.close();
boolean success = tempFile.renameTo(inputFile);
}
}

最佳答案

您的代码将从文件中读取的整行与用户输入的用户名进行比较,但您在问题中说您实际上只想与第一个管道( | )之前的第一部分进行比较。您的代码不会执行此操作。

您需要做的是从文件中读取该行,获取字符串到第一个管道符号的部分(分割字符串),然后根据分割字符串的第一部分与 lineToRemove 的比较跳过该行变量。

为了更容易,您还可以将管道符号添加到用户输入中,然后执行以下操作:

string lineToRemove = UserIn + "|";

...

if (trimmedLine.startsWith(lineToRemove)) continue;

这可以让您免于分割字符串。

<小时/>

我目前不确定 UserInput.nextLine(); 是否返回换行符。为了安全起见,您可以将上面的内容更改为:

string lineToRemove = UserIn.trim() + "|";

关于Java 从文件中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29510917/

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