0

我正在写一些文本文件然后删除它,但删除失败。

代码非常简单:

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
            }
        }
    }
}

输出是:

Deleted? false

并且有一个文件abc.txt包含helloc:.

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

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

4

5 回答 5

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) {
        }
    }
}
于 2012-09-28T13:51:17.927 回答
1

看看FileUtils.writeStringToFile()你没有做什么。

public static void writeStringToFile(File file, String data, String encoding) throws IOException {
    OutputStream out = new java.io.FileOutputStream(file);
    try {
        out.write(data.getBytes(encoding));
    } finally {
        IOUtils.closeQuietly(out);
    }
}

您会注意到out始终是关闭的,而在您的示例中,只有在抛出异常时它才会在您的catch块中关闭。write()

在 Windows 上,不能删除任何程序打开的文件。

于 2012-09-28T13:52:22.250 回答
1

如果发生异常,您只需删除文件。每次打开文件后,您都需要这样做。您可能希望将 close 放入 finally 块中。

如果您使用的是 Java 7,我考虑使用 try-with-ressources 块,它会为您关闭文件。

try (BufferedReader br = new BufferedReader(new FileReader(path))) 
{
    return br.readLine();
}
于 2012-09-28T13:51:22.470 回答
1

在你的主要方法中,

 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);

    }

您打开文件,写入文件,然后不要关闭它。Java 会为您打开文件,因此如果您想向其中添加更多信息,您可以。但是,为了能够删除该文件,您需要确保没有其他引用对其打开。您可以通过使用 file.close() 关闭 Java 为您保留的文件句柄来执行此操作。

最好的做法是在完成后始终关闭流,尤其是在向其中添加数据的情况下。否则,您可能会遇到意外打开文件的情况,或者在极端情况下会丢失您认为已经保存的数据。

于 2012-09-28T13:51:28.110 回答
1

完成文件写入后,您需要关闭 OutputStream。

try {
        out = new FileOutputStream(file);
        out.write(content.getBytes("UTF-8"));
        out.close();
    } catch (IOException e) {
        try {
            out.close();
        } catch (IOException e1) {
            // ignored
        }
    }
于 2012-09-28T13:49:56.697 回答