Java - 从File []数组中删除一些文件

时间:2014-12-02 20:55:28

标签: java arrays

我有数组File [] polFiles。一些文件可以被另一个函数删除,我编写函数来清理数组中的远程文件。例如,如果File [] polFiles中有P0,P1,P2,P3,P4,并且被P1和P2删除,则现在polFiles应包含P0,P2和P4。怎么做?我编写了简单的代码,但它会抛出任何异常和错误。

int delcount = 0;
for (File file : files) {
    if (!file.exists()) {
        delcount++;
    }
}
File[] newfiles = new File[files.length-delcount];
int fcount = 0;
for (int i = 0; i < newfiles.length; i++) {
    if (!files[i].exists()) {
        fcount++;
        for (int j = i; j < files.length-fcount-1; j++) {
            newfiles[j] = files[j+fcount];
        }
    } else {
        newfiles[i] = files[i+fcount];
    }
}
System.arraycopy(newfiles, 0, files, 0, newfiles.length);
for (int i = newfiles.length; i < files.length; i++) {
    files[i] = null;
}

哪里出错?此代码抛出Null异常并且无法正常工作。它只删除数组中的第一个文件

2 个答案:

答案 0 :(得分:3)

使用List s比使用数组更容易。除非你有充分的理由,否则放开阵列......在Guava的帮助下,这变得更加容易:

FluentIterable.from(files)
    .filter(new Predicate<File>() {
        @Override
        public boolean apply(@Nullable File file) {
            return file.exists();
        }
    }).toList();

答案 1 :(得分:2)

如果您想在没有图书馆帮助的情况下这样做,请尝试以下内容:

private File[] compactor(File[] files) {
    int deleted = 0;
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        if (file.exists()) {
            files[i - deleted] = file;
        } else {
            files[i] = null;
            deleted++;
        }
    }

    int nSize = files.length - deleted;
    File[] newFiles = new File[nSize];
    if (nSize > 0) {
        System.arraycopy(files, 0, newFiles, 0, newFiles.length);
    }
    System.out.println(Arrays.toString(newFiles));
    return newFiles;
}

只需检查是否需要添加任何边界条件。

相关问题