如何正确删除文件?

时间:2017-01-16 13:17:50

标签: java delete-file

使用org.apache.commons.io.FileUtils从img目录中删除文件时遇到问题。我正在使用此代码:

File dir = new File(".\\img");
    FileFilter fileFilter = new WildcardFileFilter(userId + ".*");
    File[] files = dir.listFiles(fileFilter);
    System.out.println("files found: " + files.length);
    for (int i = 0; i < files.length; i++) {
        boolean success = FileUtils.deleteQuietly(files[i]);
        System.out.println(files[i] + " delete result = " + success);
    }
}

实际上,该代码用于替换img目录中存在的图像文件。我需要使用新文件删除名称为n。*的所有以前存在的文件,例如n.png。如果我试图删除图像文件,我会得到变量成功的错误值,并且文件不会被删除。但不是图像文件,例如*名为.abc; * .acd; * .acdc等已成功删除。这个问题是什么情况?

2 个答案:

答案 0 :(得分:1)

试试这个:

 public DoubleEndedPriorityQueue(){
     max = new MaxPQ<Element>();
     min = new MinPQ<Element>();
 }
 public void insert(Key item){
     Element thisElement = new Element(item);
     Element thatElement = new Element(item);
     thisElement.element = thatElement;
     thatElement.element = thisElement;
     max.insert(thisElement);
     min.insert(thatElement);
 }
 private class Element{
     Key item;
     Element element;
     private Element(){}
     private Element(Key item){
         this(item,null);
     }
     private Element(Key item,Element element){
         this.item = item;
         this.element = element;
     }
 }

看看会抛出什么异常。

答案 1 :(得分:0)

此代码对我有用:

File dir = new File("/home/abhijith/.img");
        FileFilter fileFilter = new WildcardFileFilter("abc"+".*");
        File[] files = dir.listFiles(fileFilter);
        System.out.println("files found: " + files.length);
        for (int i = 0; i < files.length; i++) {
            boolean success = org.apache.commons.io.FileUtils.deleteQuietly(files[i]);
            System.out.println(files[i] + " delete result = " + success);
        }

这是输出:

files found: 1
/home/abhijith/.img/abc.jpg delete result = true