Java-从文件读取后删除文件

时间:2020-05-26 14:40:35

标签: java

我试图弄清为什么inputFile.delete()无法删除文件。在查看了多个主题之后,似乎文件仍在使用中,因此它不会被删除。但我不知道。我想念什么?

File inputFile = new File("data/Accounts.txt");
File tempFile = new File("data/tmp.txt");

try {
    tempFile.createNewFile();
    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
    String line;

    int i = 0;
    for (User u : data) {
        String toRemove = getIDByUsername(username);
        while ((line = reader.readLine()) != null) {
            if (line.contains(toRemove + " ")) {
                line = (i + " " + username + " " + getStatusByUsername(username) + " " + password);
            }
            writer.write(line + "\n");
            i++;
        }
    }
    reader.close();
    writer.close();
} catch (FileNotFoundException e) {
    ex.FileNotFound();
} catch (IOException ee) {
    ex.IOException();
} finally {
    inputFile.delete();
    tempFile.renameTo(inputFile);
}

2 个答案:

答案 0 :(得分:3)

使用java.nio可以使您变得更短,更轻松:

public static void main(String[] args) {
    // provide the path to your file, (might have to be an absolute path!)
    Path filePath = Paths.get("data/Accounts.txt");

    // lines go here, initialize it as empty list
    List<String> lines = new ArrayList<>();

    try {
        // read all lines (alternatively, you can stream them by Files.lines(...)
        lines = Files.readAllLines(filePath);
        // do your logic here, this is just a very simple output of the content
        System.out.println(String.join(" ", lines));
        // delete the file
        Files.delete(filePath);
    } catch (FileNotFoundException fnfe) {
        // handle the situation of a non existing file (wrong path or similar)
        System.err.println("The file at " + filePath.toAbsolutePath().toString()
                + " could not be found." + System.lineSeparator()
                + fnfe.toString());
    } catch (FileSystemException fse) {
        // handle the situation of an inaccessible file
        System.err.println("The file at " + filePath.toAbsolutePath().toString()
                + " could not be accessed:" + System.lineSeparator()
                + fse.toString());
    } catch (IOException ioe) {
        // catch unexpected IOExceptions that might be thrown
        System.err.println("An unexpected IOException was thrown:" + System.lineSeparator()
                + ioe.toString());
    }
}

这将打印文件的内容,然后将其删除。
您将希望做一些不同的事情,而不仅仅是打印内容,但这也是可能的;-)尝试一下...

答案 1 :(得分:0)

我试图弄清楚为什么inputFile.delete()无法删除文件。

这是因为旧文件API特别以这种方式糟糕透顶:它无法告诉您某些失败的原因。它所能做的就是返回'false'。

请参阅@deHaar的另一个答案,其中显示了如何使用较新的API来执行此操作。除了提供更简洁的代码和更新的API给您更多选择之外,更新的API还解决了此问题,其中各种方法(例如File.delete()不能告诉您无法执行您的要求的原因。

您的代码有很多很多问题,这就是为什么我强烈建议您进行deHaar尝试的原因。发挥作用:

  1. 您没有正确关闭资源;如果发生异常,您的文件处理程序将保持打开状态。
  2. 这里的读写都是通过“平台默认编码”完成的,无论如何。基本上,永远不要使用那些FileReaderFileWriter的构造函数。幸运的是,如果您未能指定编码方式,那么新API的默认默认设置为UTF_8。
  3. 您的异常处理不是很好(您可能会丢弃任何有用的消息,例如ex.FileNotFound()可能在此处执行的操作)-即使发生异常,您仍会尝试删除并替换,然后失败,因为文件句柄仍处于打开状态。
  4. 该方法应称为getIdByUsername
  5. 您的toRemove字符串每次都相同,或者至少,username变量在您遍历时似乎没有更新。如果确实没有更新,则将该行移出循环。