欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > Java学习,目录是否为空

Java学习,目录是否为空

2025/2/25 10:30:34 来源:https://blog.csdn.net/xuann/article/details/144871911  浏览:    关键词:Java学习,目录是否为空

Java 要判断一个目录是否为空,可以使用java.nio.file包中Files和 Paths类来遍历目录内容,如果目录没有任何文件或子目录,那么它就是空的。

使用java.nio.file中Files与Paths:
import java.nio.file.*;
import java.io.IOException;
 
public class CheckEmptyDirectory {
    public static void main(String[] args) {
        // 要检查的目录路径
        Path directoryPath = Paths.get("path/to/directory");
 
        try {
            // 检查目录是否为空
            boolean isEmpty = isDirectoryEmpty(directoryPath); 
            // 输出结果
            if (isEmpty) {
                System.out.println("目录是空的: " + directoryPath);
            } else {
                System.out.println("目录不是空的: " + directoryPath);
            }
        } catch (IOException e) {
            // 处理异常
            System.err.println("检查目录时出错: " + e.getMessage());
        }
    }
 
    /**
     * 判断目录是否为空
     *
     * @param dir 要检查的目录
     * @return 如果目录为空,则返回 true;否则返回 false
     * @throws IOException 如果在访问目录时发生 I/O 错误
     */
    public static boolean isDirectoryEmpty(Path dir) throws IOException {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            return !stream.iterator().hasNext();
        }
    }
}

使用java.io.File进行判断:

import java.io.File; 
public class Main
{
    public static void main(String[] args)
    {
        File file = new File("./testdir");  // 当前目录下testdir
        if(file.isDirectory()){
            if(file.list().length>0){
                System.out.println("目录不为空!");
            }else{
                System.out.println("目录为空!");
            }
        }else{
            System.out.println("这不是一个目录!");
        }
    }
}

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词