从txt文件中删除特定行

时间:2018-11-11 11:14:24

标签: java javafx text-files

您好,我需要在ID搜索后删除文本文件中的特定行。 ID = 2

  

students.txt

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

搜索并删除后得到:

  

students.txt

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

但是不能正常工作

到目前为止的

代码:

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

1 个答案:

答案 0 :(得分:1)

如果您想通过行号删除行,我想您可以像这样更改代码。您可以将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);
    }
}