无法删除java中的文件? [英] Can't delete files in java?

查看:119
本文介绍了无法删除java中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除文件夹中的所有文件: -

I am trying to delete all files in a folder:-

    import java.io.*;
public class AddService {   
    public static void main(String args[]){
        File folder=new File("inputs");
        File[] listOfFiles=folder.listFiles();
        for(File file:listOfFiles){
            if(file.delete())
                System.out.println("File deleted");
            else
                System.out.println("File not deleted");
        }
    }
}

我收到回复文件未删除并且文件未被删除。我的代码出了什么问题?

I am getting response "File not deleted" and the file isn't getting deleted. What's wrong with my code?

推荐答案

为什么文件无法删除有很多原因;它可能不存在,它可能是非空的目录,您可能没有关闭所有使用它的资源,并且您的程序可能没有这样做的权限,仅举几例。

There are any number of reasons why a file cannot be deleted; it may not exist, it may be a non-empty directory, you may not have closed all resources using it, and your program may not have permission to do so, to name a few.

不幸的是 File.delete() 方法提供的原因很少;它几乎取决于你四处寻找并弄明白。但是有好消息;你不想在第一时间使用文件

Java 7引入了新的 java.nio.file 包,这是一个更强大的文件访问API。它提供了抽象的概念 路径 并将具体操作分为 文件 类,特别是它提供了 Files.delete() 记录以提出明确的例外情况,描述删除可能失败的原因。

Java 7 introduced the new java.nio.file package which is a much more robust file access API. It provides the concept of an abstract Path and separates concrete operations into the Files class, in particular it provides Files.delete() which is documented to raise clear exceptions describing the reasons deletion might fail.

使用路径文件;你会很高兴的。

Use Path and Files; you'll be glad you did.

这篇关于无法删除java中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆