简体   繁体   中英

How to delete or remove a specific line from a text file

I was trying to delete a line from a file. I've search on the internet. And i made a method. Here is it.

public void removeLine(BufferedReader br , File f,  String Line) throws IOException{
    File temp = new File("temp.txt");
    BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
    String removeID = Line;
    String currentLine;
    while((currentLine = br.readLine()) != null){
        String trimmedLine = currentLine.trim();
        if(trimmedLine.equals(removeID)){
            currentLine = "";
        }
        bw.write(currentLine + System.getProperty("line.separator"));

    }
    temp.renameTo(f);
    bw.close();
    br.close();
}   

I don't know what is wrong with this method. Could you help me?

Here is where i use this method

delete.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent evt) {


        BufferedReader br = null;
    try{
    String enterID2 =  enterID1.getText().trim();
        File books = new File("books.txt");
         br = new BufferedReader(new FileReader(books));
         removeLine(br , books, enterID2);
         System.out.println("done");

    }catch (NumberFormatException e1) {
               System.out.println("This is not a number");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



    }
    });

Delete is a JButton. No error recieved.

Try this code:

public static void removeLine(BufferedReader br , File f,  String Line) throws IOException{
    File temp = new File("temp.txt");
    BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
    String removeID = Line;
    String currentLine;
    while((currentLine = br.readLine()) != null){
        String trimmedLine = currentLine.trim();
        if(trimmedLine.equals(removeID)){
            currentLine = "";
        }
        bw.write(currentLine + System.getProperty("line.separator"));

    }
    bw.close();
    br.close();
    boolean delete = f.delete();
    boolean b = temp.renameTo(f);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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