首页 > 解决方案 > 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);
}

标签: java

解决方案


通过使用,您可以更短更轻松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());
    }
}

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


推荐阅读