如何从文本文件中删除或删除特定行

时间:2017-07-20 09:43:13

标签: java

我试图从文件中删除一行。我在互联网上搜索。我做了一个方法。就是这样。

{{ posts.links | raw }}

我不知道这个方法有什么问题。你能帮帮我吗?

这是我使用此方法的地方

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

删除是一个JButton。没有收到任何错误。

1 个答案:

答案 0 :(得分:1)

试试这段代码:

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