java - 从txt文件中删除特定行

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

最佳答案

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

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

相关文章:

python - 从文本文件创建字典 Python Numpy

java - DES-加密字节数组,java

java - 将文档或文件夹从 Documentum 中的一个存储库移动到另一个存储库

java - 如何使用 css 在 JavaFX 中更改 ListView 单元格的文本颜色

java - 如何使用javaFX播放多个连续的声音文件?

java - 如何在java中搜索文本文件中的某个单词

Matlab:如何通过指定 header 名称读取和提取矩阵?

java - Dining Philosophers 代码中发生的饥饿

java - 如何在静态 main 方法中将数据添加到数组列表中

JavaFX SceneBuilder 2.0 不会为 fx :root as main layout tag 的自定义组件打开 FXML