如何删除Java中文本文件的最后一行?

时间:2017-03-23 03:14:31

标签: java file bufferedreader

我有一个包含几个字符串的文件。 例如:

Mike1111
Chris2222
Brian3333

我正在尝试编写代码来删除该文件中的一行。但是,当我删除Chris时,它变为:

Mike1111
Brian3333
(空行)

空白行是个问题,因为当我添加另一个字符串时,它会出现在空白行之后,而不是在它的位置。先感谢您。这是我的代码:

public void deleteUser(String u, String p) throws IOException {
    username = u;
    pin = p;

    File userAccountFolder = new File("userLogin.txt");
    File temporaryFile = new File("temporaryFile.txt");

    BufferedReader buffReader = new BufferedReader(new FileReader(userAccountFolder));
    BufferedWriter buffWriter = new BufferedWriter(new FileWriter(temporaryFile));

    String lineToRemoveFromFile = username + pin;
    String lineFromUserFile;

    while ((lineFromUserFile = buffReader.readLine()) != null) {

        String trimmedLine = lineFromUserFile.trim();
        if (trimmedLine.equals(lineToRemoveFromFile)) {
          continue;
        }

        buffWriter.append(lineFromUserFile + System.getProperty("line.separator"));
    }
    buffWriter.close();
    buffReader.close();

    boolean removed = temporaryFile.renameTo(userAccountFolder);
    if (removed == true) {
        System.out.println(username + "'s account has been removed.");

    }

}

2 个答案:

答案 0 :(得分:0)

这将解决问题,添加一个布尔检查。

        BufferedReader buffReader = new BufferedReader(new FileReader(userAccountFolder));
        BufferedWriter buffWriter = new BufferedWriter(new FileWriter(temporaryFile));

        String lineToRemoveFromFile = username + pin;
        String lineFromUserFile;

        boolean addnewLine = false;

        while ((lineFromUserFile = buffReader.readLine()) != null) {

            String trimmedLine = lineFromUserFile.trim();
            if (trimmedLine.equals(lineToRemoveFromFile)) {
                continue;
            }

            if (addnewLine) {
                buffWriter.newLine();
            } else {
                addnewLine = true;
            }
            buffWriter.append(lineFromUserFile);

        }
        buffWriter.close();
        buffReader.close();

答案 1 :(得分:0)

这里的问题是,使用System.getProperty("line.separator"),即使没有更多行进入,也会在临时文件的末尾附加一行。下面的代码试图避免创建冗余的结束行:

    String lineFromUserFile = null;
    boolean needAddNewLine = false;
    while ((lineFromUserFile = buffReader.readLine()) != null) {
        if (!lineFromUserFile.trim().equals(lineToRemoveFromFile)) {
            if (needAddNewLine) {
                buffWriter.newLine();
            }
            needAddNewLine = true;
            buffWriter.write(lineFromUserFile);
        }
    }