Java中的listFiles()无法获取所有文件 [英] listFiles() in Java fails to get all files
问题描述
我写了这个函数,看起来好像是okey,但是如果当前目录中有多个文件夹,并且没有文件,就会失败。它只进入第一个文件夹,并在那里工作,忽略其他文件夹。如何修复这个bug?
public static void getAllFiles(File folder,List< File> 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);
$ div class =h2_lin>解决方案
public List< Path> findAllFilesInDirectory(Path pathToDir)throws IOException {
final List< Path> pathsToFiles = new ArrayList<>();
Files.walkFileTree(pathToDir,new SimpleFileVisitor< Path>(){
@Override $ b $ public FileVisitResult visitFile(Path file,BasicFileAttributes attrs)throws IOException {
if (Files.isRegularFile(file)){
pathsToFiles.add(file);
}
return FileVisitResult.CONTINUE;
}
});
return pathsToFiles;
$ / code>
使用NIO.2必须至少有一个Java 1.7版本。
文档:
http://docs.oracle.com/javase/tutorial/essential/io/walk.html
教程:
$ b http://www.javabeat.net/visiting-all-the-files-and-directories-for-a-directory-in- java-using-nio2 /
http://www.srccodes.com/p/article/20/java-file-and-directory-operations-made-easy- in-jdk7
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<File> 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<Path> findAllFilesInDirectory(Path pathToDir) throws IOException {
final List<Path> pathsToFiles = new ArrayList<>();
Files.walkFileTree(pathToDir, new SimpleFileVisitor<Path>() {
@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:
http://docs.oracle.com/javase/tutorial/essential/io/walk.html
Tutorials:
http://www.javabeat.net/visiting-all-the-files-and-directories-for-a-directory-in-java-using-nio2/
http://www.srccodes.com/p/article/20/java-file-and-directory-operations-made-easy-in-jdk7
这篇关于Java中的listFiles()无法获取所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!