向其中写入一些数据后无法删除该文件,哪里出了问题?

Fre*_*ind 0 java file-io file delete-file

我在文件中写入一些文本,然后将其删除,但是删除失败。

代码很简单:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class TestFile {

    public static void main(String[] args) throws IOException {
        File file = new File("c:\\abc.txt");
        writeFile(file, "hello");

        // delete the file
        boolean deleted = file.delete();
        System.out.println("Deleted? " + deleted);

    }

    public static void writeFile(File file, String content) throws IOException {
        OutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(content.getBytes("UTF-8"));
        } catch (IOException e) {
            try {
                out.close();
            } catch (IOException e1) {
                // ignored
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出为:

Deleted? false
Run Code Online (Sandbox Code Playgroud)

并且还有一个文件abc.txt包含hello在下面c:

然后我改用FileUtils.writeStringToFile(...)from commons-io.jar,该文件将被删除。

但是我不知道我的代码在哪里出了问题,请帮助我找出来。

Pet*_*rey 5

如果得到IOException,则仅关闭文件。

将其更改为一个finally块,您将能够关闭和删除该文件。

public static void writeFile(File file, String content) throws IOException {
    OutputStream out = new FileOutputStream(file);
    try {
        out.write(content.getBytes("UTF-8"));
    } finally {
        try {
            out.close();
        } catch (IOException ignored) {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)