简体   繁体   English

Java中如何判断一个目录是否为空

[英]How to check if a directory is empty in Java

I'd like to check if directory is empty in Java. But there is a possibility that there are many files in that directory so I'd like to do it without querying its file list, if possible.我想检查 Java 中的目录是否为空。但是该目录中可能有很多文件,所以如果可能的话,我想在不查询其文件列表的情况下执行此操作。

With JDK7 you can use Files.newDirectoryStream to open the directory and then use the iterator's hasNext() method to test there are any files to iterator over (don't forgot to close the stream).使用 JDK7,您可以使用 Files.newDirectoryStream 打开目录,然后使用迭代器的 hasNext() 方法来测试是否有要迭代的文件(不要忘记关闭流)。 This should work better for huge directories or where the directory is on a remote file system when compared to the java.io.File list methods.与 java.io.File 列表方法相比,这对于大型目录或目录位于远程文件系统上的位置应该更有效。

Example:例子:

private static boolean isDirEmpty(final Path directory) throws IOException {
    try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) {
        return !dirStream.iterator().hasNext();
    }
}
File parentDir =  file.getParentFile();
if(parentDir.isDirectory() && parentDir.list().length == 0) {
    LOGGER.info("Directory is empty");
} else {
    LOGGER.info("Directory is not empty");
}
if(!Files.list(Paths.get(directory)).findAny().isPresent()){
    Files.delete(Paths.get(directory));
 }

As Files.list Return a lazily populated Stream it will solve your execution time related issue.由于 Files.list 返回一个延迟填充的 Stream 它将解决与执行时间相关的问题。

Considering from java.io.File source code , list() method does:java.io.File source code考虑, list()方法做:

    public java.lang.String[] list() {
    ...
        byte[][] implList = listImpl(bs);
        if (implList == null) {
           // empty list
           return new String[0];
        }     
     ...
     }

     private synchronized static native byte[][] listImpl(byte[] path);

It calls a native method passing a byte array to get files from it.它调用传递字节数组的本机方法以从中获取文件。 If a method returns null it means directory is empty.如果方法返回null ,则表示目录为空。

Which means , they don't even have a native method, to check for directory emptiness without listing files, so there is no way they would have an implementation in java for checking if directory is empty.这意味着,他们甚至没有本地方法来检查目录是否为空而不列出文件,因此他们无法在 java 中实现检查目录是否为空。

Outcome : checking if directory is empty without listing files is not implemented in java, yet.结果:在 java 中还没有实现在不列出文件的情况下检查目录是否为空。

boolean isEmptyDirectory(Path dir) throws IOException {
    try (var entries = Files.list(dir)) {
        return entries.count() == 0;
    }
}

Similar to @Minnow's solution (but with less method calls), this solution has the benefit "As Files.list Return a lazily populated Stream it will solve your execution time related issue."类似于@Minnow 的解决方案(但方法调用较少),此解决方案具有“作为 Files.list 返回延迟填充的 Stream 它将解决与执行时间相关的问题”的好处。

This is a dirty workaround, but you can try do delete it (with the delete method), and if the delete operation fails, then the directory is not empty, if it succeeds, then it is empty (but you have to re-create it, and that's not neat).这是一个肮脏的解决方法,但你可以尝试删除它(使用delete方法),如果删除操作失败,则目录不为空,如果成功,则目录为空(但你必须重新创建它,这并不整洁)。 I'll continue searching for a better solution.我会继续寻找更好的解决方案。

EDIT : I've found walkFileTree from java.nio.file.Files class: http://download.java.net/jdk7/docs/api/java/nio/file/Files.html#walkFileTree(java.nio.file.Path , java.nio.file.FileVisitor) Problem is that this is Java 7 only.编辑:我从 java.nio.file.Files class: http://download.java.net/jdk7/docs/api/java/nio/file/Files.html#walkFileTree(java.nio.file .Path , java.nio.file.FileVisitor) 问题是这只是 Java 7。

I've searched SO for other questions related to this very issue (listing files in a directory w/o using list() which allocates memory for a big array) and the answer is quite always "you can't, unless you use JNI", which is both platform dependent and ugly.我已经搜索了与这个问题相关的其他问题(在不使用 list() 的目录中列出文件,它为一个大数组分配了 memory),答案总是“你不能,除非你使用 JNI ",这既依赖于平台又丑陋。

If you can live with platform dependent code - you can try using actual native code by loading a system library and using its APIs.如果您可以忍受依赖于平台的代码 - 您可以通过加载系统库并使用其 API 来尝试使用实际的本机代码。

In Windows for example you have a Win32 API named FindFirstFile() with the directory name ( without a trailing backslash).例如,在 Windows 中,您有一个名为FindFirstFile()Win32 API以及目录名称(没有尾部反斜杠)。 If it returns something other than .如果它返回的不是. and .. you know the directory isn't empty.并且..您知道该目录不为空。 It will not list all the files so it's much faster than file.list() .它不会列出所有文件,因此它比file.list()快得多。

The equivalent on Unix isopendir . Unix 上的等价物是opendir For your purposes the logic would be the same.出于您的目的,逻辑是相同的。

Of course - calling native methods has a price on usability and the initial library loading which should be negated by the time it will save on the FS queries.当然 - 调用本机方法在可用性和初始库加载方面是有代价的,当它保存在 FS 查询上时,应该取消这些加载。

     Path checkIfEmpty=Paths.get("Pathtofile");
     DirectoryStream<Path> ds = Files.newDirectoryStream(checkIfEmpty);
     Iterator files = ds.iterator();
     if(!files.hasNext())
         Files.deleteIfExists(Paths.get(checkIfEmpty.toString()));

I'd like to check if directory is empty in Java.我想检查 Java 中的目录是否为空。 But there is a possibility that there are many files in that directory so I'd like to do it without querying its file list, if possible.但是该目录中可能有很多文件,因此如果可能,我想在不查询其文件列表的情况下执行此操作。

I also had this Confusion for a Long time about how to check if the Directory was empty or not But the Answer is Quite Simple use关于如何检查目录是否为空,我也有很长一段时间的困惑但是答案很简单使用

class isFileEmpty{
public static void main(String args[]){
File d = new File(//Path of the Directory you want to check or open);
String path = d.getAbsolutePath().toString();
File dir = new File(path);
File[] files = dir.listFiles();
if(!dir.exists()){
System.out.Println("Directory is Empty");
}
else{
for(int i =0;i<files.length;i++){
System.out.Println(files[i])
           }
       }
   }
}

I want to add to answer of Developer.我想添加到开发人员的答案中。 Checking is it directory or not should not be in one If operator, because you will have mistake in logic.检查是否是目录不应该在一个 If 运算符中,因为你会在逻辑上出错。 First of all you checking is it directory or not, and only after that you checking directory consistensy, becouse you will get wrong answer if the tranfered to method directory is not exist.首先你检查它是不是目录,然后才检查目录一致性,因为如果转移到方法目录不存在你会得到错误的答案。 Just check it.只是检查一下。 Should be like this:应该是这样的:

if (file.isDirectory()) {
    if( file.list().length == 0) {
        logger.info("Directory is empty");
        return false;
    } else {
        logger.info("Directory is not empty");
        return true;
    }
} else {
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM