简体   繁体   English

从txt文件中删除特定行

[英]Remove specific line from txt file

Hello i need to delete a specific line from text file after ID search pg ID=2 您好,我需要在ID搜索pg ID = 2之后从文本文件中删除特定行

students.txt students.txt

1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman

And after search and delete to get: 并且经过搜索和删除后得到:

students.txt students.txt

1,Giannis,Oreos,Man  
3,Maria,Oaka,Woman

But is not working properly 但是不能正常工作

Code so far: 到目前为止的代码:

    @FXML
    TextField  ID2;
    @FXML       
        public void UseDelete() throws IOException {
            File inputFile = new File("src/inware/students.txt");
            File tempFile = new File("src/inware/studentsTemp.txt");

            BufferedReader reader = new BufferedReader(new FileReader(inputFile));
            BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

            String lineToRemove = ID2.getText();
            String currentLine;

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

If you want to remove a line by a line number I guess you can do a change to your code like this. 如果您想通过行号删除行,我想您可以像这样更改代码。 You can give the int value of Id to the lineToRemove variable instead of my hard coded value 您可以将Id的int值赋予lineToRemove变量,而不是我的硬编码值

import java.io.*;

public class A {

    public static void main(String[] args) throws IOException {
        new A().useDelete();
    }

    public void useDelete() throws IOException {
        File inputFile = new File("src/inware/students.txt");
        File tempFile = new File("src/inware/studentsTemp.txt");

        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

        int lineToRemove = 2;
        String currentLine;
        int count = 0;

        while ((currentLine = reader.readLine()) != null) {
            count++;
            if (count == lineToRemove) {
                continue;
            }
            writer.write(currentLine + System.getProperty("line.separator"));
        }
        writer.close();
        reader.close();
        inputFile.delete();
        tempFile.renameTo(inputFile);
    }
}

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

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