简体   繁体   English

Java从文件删除行

[英]Java Delete Line from File

the code below is from a reference i saw online, so there might be some similarities i'm trying to implement the code to remove an entire line based on the 1st field in this instance it is (aaaa or bbbb) the file which has a delimiter "|", but it is not working. 下面的代码来自我在网上看到的参考,因此可能存在一些相似之处,我正在尝试实现代码以在此实例中基于第一个字段删除整行,它是(aaaa或bbbb)文件,其中包含分隔符“ |”,但不起作用。 Hope someone can advise me on this. 希望有人可以给我建议。 Do i need to split the line first? 我需要先分线吗? or my method is wrong? 还是我的方法不对?

data in player.dat (eg) Player.dat中的数据(例如)

bbbb|aaaaa|cccc
aaaa|bbbbbb|cccc

Code is below 代码如下

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);
    }
}

Your code compares the entire line it reads from the file to the user name the user enters, but you say in your question that you actually only want to compare to the first part up to the first pipe ( | ). 您的代码会将从文件中读取的整个行与用户输入的用户名进行比较,但是您在问题中说,您实际上只想与第一部分进行比较,直到第一个管道( | )。 Your code doesn't do that. 您的代码无法做到这一点。

What you need to do is read the line from the file, get the part of the string up to the first pipe symbol (split the string) and skip the line based on comparing the first part of the split string to the lineToRemove variable. 您需要做的是从文件中读取行,将字符串的一部分向上移动到第一个管道符号(拆分字符串),然后根据将拆分字符串的第一部分与lineToRemove变量进行比较,跳过该行。

To make it easier, you could also add the pipe symbol to the user input and then do this: 为了简化操作,您还可以将管道符号添加到用户输入中,然后执行以下操作:

string lineToRemove = UserIn + "|";

...

if (trimmedLine.startsWith(lineToRemove)) continue;

This spares you from splitting the string. 这样可以避免拆分字符串。


I'm currently not sure whether UserInput.nextLine(); 我目前不确定是否UserInput.nextLine(); returns the newline character or not. 是否返回换行符。 To be safe here, you could change the above to: 为了安全起见,您可以将以上内容更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM