java listfiles,Java中的listFiles()无法获取所有文件

博客内容讲述了在Java中遍历当前目录下所有文件时遇到的问题,当目录包含多个子文件夹时,原始函数只处理第一个文件夹并忽略其余。作者建议使用NIO.2的`walkFileTree`方法来解决这个问题,并提供了修改后的代码示例。这个新方法可以遍历所有子文件夹并找到所有文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I wrote this function and it seemed okey but it fails if there are more than one folders in the current directory and no files. It enters only the first folder and does it job there and ignores the other folders. How can I fix this bug?

public static void getAllFiles(File folder, List result) {

File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {

if (listOfFiles[i].isFile()) {

result.add(listOfFiles[i]);

}

if (listOfFiles[i].isDirectory()) {

getAllFiles(listOfFiles[i], result);

}

}

}

解决方案

Maybe you should try walkFileTree method from NIO.2:

public List findAllFilesInDirectory(Path pathToDir) throws IOException {

final List pathsToFiles = new ArrayList<>();

Files.walkFileTree(pathToDir, new SimpleFileVisitor() {

@Override

public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

if (Files.isRegularFile(file)) {

pathsToFiles.add(file);

}

return FileVisitResult.CONTINUE;

}

});

return pathsToFiles;

}

To using NIO.2 You have to have at least a Java 1.7 version.

Documentation:

Tutorials:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值