如何使用java从文本文件中逐行读取和删除

时间:2017-04-08 07:42:22

标签: java bufferedreader filereader printwriter

我有一个包含2行喜欢的文本文件

  • Hello World 1。
  • Hello World 2。

我想逐一阅读并删除这两行。成功地我读了那两行但是当我删除那些然后它失败了。这是我的代码。

@FXML
public void buttonLineDeleteAction(ActionEvent event) throws IOException {
    try {
        String line = null;
        final File fileGpNumber = new File(filePath);
        FileReader fileReader = new FileReader(fileGpNumber);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        while ((line = bufferedReader.readLine()) != null) {

            System.out.println("Line--- " + line);
            boolean result = removeLineFromFile(line);
            System.out.println("Result---> " + result);
        }
    } catch (IOException e) {
        System.out.println("IOException " + e);
    }
}

并删除此方法。

private boolean removeLineFromFile(String lineToRemove) {
    boolean isDeleted = false;
    try {
        File inFile = new File(filePath);
        File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
        BufferedReader br = new BufferedReader(new FileReader(filePath));
        PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
        String line;

        //Read from the original file and write to the new 
        //unless content matches data to be removed.
        while ((line = br.readLine()) != null) {
            if (!line.trim().equals(lineToRemove)) {
                pw.println(line);
                pw.flush();
                isDeleted = false;
            } else {
                isDeleted = true;
            }
        }
        pw.close();
        br.close();

        //Delete the original file
        if (inFile.delete()) {
            isDeleted = true;
        } else {
            isDeleted = false;
            System.out.println("Could not delete file.");
        }
        //Rename the new file to the filename the original file had.
        if (tempFile.renameTo(inFile)) {
          isDeleted = true;
        } else {
         System.out.println("Could not rename file.");
         isDeleted = false;
        }

    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return isDeleted;
}

现在删除我的tempFile中的那行但是删除inFile并重命名thetempFile文件时出现问题。 这是我的输出

Line--- Hello World 1.
Could not delete file.
Could not rename file.
Result---> false
Line--- Hello World 2.
Could not delete file.
Could not rename file.
Result---> false

请帮助我。提前谢谢。

1 个答案:

答案 0 :(得分:0)

问题是您无法删除buttonLineDeleteAction中的第一个文件,因为它仍然被close方法锁定(因为您正在阅读文件内容和你没有$scope.datas文件阅读器对象。

因此,您需要按照以下步骤操作:

(1)找出所有必需的行并将其收集到列表中并关闭文件

(2)创建一个新文件并从List中写入内容并关闭文件

(3)立即删除旧文件

(4)重命名新文件并关闭新文件