簡體   English   中英

從txt文件中刪除特定行

[英]Remove specific line from txt file

您好,我需要在ID搜索pg 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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM