Java“文件.删除()”不删除指定文件

发布于 2024-10-08 08:51:23 字数 499 浏览 5 评论 0原文

目前我必须删除该文件,但它不起作用。我以为这可能是权限问题或其他问题,但事实并非如此。我正在测试的文件是空的并且存在,所以不确定为什么它不删除它。

UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
file.delete();

任何帮助将不胜感激!

我现在有:

File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();

尝试在运行时找到正确的路径,以便如果程序传输到另一台计算机,它仍然可以找到该文件。

This is currently what I have to delete the file but it's not working. I thought it may be permission problems or something but it wasn't. The file that I am testing with is empty and exists, so not sure why it doesn't delete it.

UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
file.delete();

Any help would be GREATLY appreciated!

I now have:

File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();

To try and find the correct path at run time so that if the program is transferred to a different computer it will still find the file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

深爱不及久伴 2024-10-15 08:51:23

该问题也可能是由于您忘记关闭任何输出流造成的。就我而言,我在文件被删除之前正在处理该文件。然而,在文件操作的一处,我忘记关闭我用来写入稍后尝试删除的文件的输出流。

The problem could also be due to any output streams that you have forgotten to close. In my case I was working with the file before the file being deleted. However at one place in the file operations, I had forgotten to close an output stream that I used to write to the file that was attempted to delete later.

策马西风 2024-10-15 08:51:23

请务必找到您当前的工作目录,并写入相对于它的文件路径。

此代码:

File here = new File(".");
System.out.println(here.getAbsolutePath());

...将打印出该目录。

另外,与您的问题无关,请尝试使用 File.separator 保持与操作系统无关。反斜杠仅在 Windows 上有效。

Be sure to find out your current working directory, and write your filepath relative to it.

This code:

File here = new File(".");
System.out.println(here.getAbsolutePath());

... will print out that directory.

Also, unrelated to your question, try to use File.separator to remain OS-independent. Backslashes work only on Windows.

北笙凉宸 2024-10-15 08:51:23

我遇到了同样的问题!然后意识到我的目录不为空。我在另一个线程中找到了解决方案:无法通过Java删除目录

/**
 * Force deletion of directory
 * @param path
 * @return
 */
static public boolean deleteDirectory(File path) {
    if (path.exists()) {
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                deleteDirectory(files[i]);
            } else {
                files[i].delete();
            }
        }
    }
    return (path.delete());
}

I got the same problem! then realized that my directory was not empty. I found the solution in another thread: not able to delete the directory through Java

/**
 * Force deletion of directory
 * @param path
 * @return
 */
static public boolean deleteDirectory(File path) {
    if (path.exists()) {
        File[] files = path.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                deleteDirectory(files[i]);
            } else {
                files[i].delete();
            }
        }
    }
    return (path.delete());
}
那伤。 2024-10-15 08:51:23

尝试关闭您之前在其他方法中打开的所有 FileOutputStream/FileInputStream ,然后尝试删除,效果非常好。

Try closing all the FileOutputStream/FileInputStream you've opened earlier in other methods ,then try deleting ,worked like a charm.

盛装女皇 2024-10-15 08:51:23

我怀疑问题出在路径不正确。试试这个:

UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
if (file.exists()) {
    file.delete();
} else {
    System.err.println(
        "I cannot find '" + file + "' ('" + file.getAbsolutePath() + "')");
}

I suspect that the problem is that the path is incorrect. Try this:

UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
if (file.exists()) {
    file.delete();
} else {
    System.err.println(
        "I cannot find '" + file + "' ('" + file.getAbsolutePath() + "')");
}
心欲静而疯不止 2024-10-15 08:51:23

如果要删除文件,请先关闭所有连接和流。
之后删除该文件。

If you want to delete file first close all the connections and streams.
after that delete the file.

北方的巷 2024-10-15 08:51:23

就我而言,由于未处理的异常, close() 没有执行。

void method() throws Exception {
    FileInputStream fis = new FileInputStream(fileName);
    parse(fis);
    fis.close();
}

假设在 parse() 上抛出异常,该方法未处理该异常,因此文件未关闭,接下来,文件正在被删除,并且删除语句失败,并且不删除。

所以,我有这样的代码,然后它就工作了……

    try {
        parse(fis);
    }
    catch (Exception ex) {
        fis.close();
        throw ex;
    }

如此基本的 Java,有时我们会忽略这一点。

In my case it was the close() that was not executing due to unhandled exception.

void method() throws Exception {
    FileInputStream fis = new FileInputStream(fileName);
    parse(fis);
    fis.close();
}

Assume exception is being thrown on the parse(), which is not handled in this method and therefore the file is not closed, down the road, the file is being deleted, and that delete statement fails, and do not delete.

So, instead I had the code like this, then it worked...

    try {
        parse(fis);
    }
    catch (Exception ex) {
        fis.close();
        throw ex;
    }

so basic Java, which sometimes we overlook.

千笙结 2024-10-15 08:51:23

正如其他答案所示,在 Windows 上您无法删除打开的文件。然而,可以阻止文件在 Windows 上被删除的另一件事是,如果它被映射到 MappedByteBuffer(或 DirectByteBuffer),如果是这样,该文件在字节缓冲区被垃圾回收之前无法删除。有一些相对安全的代码可以在垃圾收集之前强制关闭(清理)DirectByteBufferhttps://github.com/classgraph/classgraph/blob/master/src/main/java/ nonapi/io/github/classgraph/utils/FileUtils.java#L606 清理ByteBuffer后,您可以删除该文件。但是,请确保清理后不再使用 ByteBuffer,否则 JVM 将崩溃。

As other answers indicate, on Windows you cannot delete a file that is open. However one other thing that can stop a file from being deleted on Windows is if it is is mmap'd to a MappedByteBuffer (or DirectByteBuffer) -- if so, the file cannot be deleted until the byte buffer is garbage collected. There is some relatively safe code for forcibly closing (cleaning) a DirectByteBuffer before it is garbage collected here: https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L606 After cleaning the ByteBuffer, you can delete the file. However, make sure you never use the ByteBuffer again after cleaning it, or the JVM will crash.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文