如何通过Java读取文件夹中的所有文件?使用哪个API无关紧要。
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);
Files.walk API 是从 Java 8 开始可用。
try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
}
这个示例使用了API指南中推荐的try-with-resources模式。它确保无论什么情况下都会关闭流。
getName()
方法只会返回其所在目录中文件的名称,该目录可能是原始目录的子目录。如果您打算使用此信息来查找文件,则可能会发现getPath()
方法返回的路径更有用。 - Tim Parentifilter
方法。然后就不再需要使用forEach。请参见此处-> https://dev59.com/PXI-5IYBdhLWcg3wc4Cw#26215931 - Julian PielesFile folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
}
}
Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
以下代码会打印文件夹中的所有文件,但排除所有目录。如果你需要一个列表,可以使用以下代码:
Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.collect(Collectors.toList())
List<File>
而不是List<Path>
,只需要进行映射即可:List<File> filesInFolder = Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.map(Path::toFile)
.collect(Collectors.toList());
java.nio.file.Path
吗?我刚刚检查了toFile()
方法,即使在Java 8之前也应该存在 -> http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#toFile() - Julian Pieles在这个话题上使用新的Java 8函数的所有答案都忽略了关闭流。 接受答案中的示例应该是:
try (Stream<Path> filePathStream=Files.walk(Paths.get("/home/you/Desktop"))) {
filePathStream.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
}
从Files.walk
方法的javadoc中:
返回的流封装了一个或多个DirectoryStreams。如果需要及时释放文件系统资源,应使用try-with-resources结构来确保在流操作完成后调用流的close方法。
关于获取目录中所有文件的说明。
方法Files.walk(path)
将通过遍历给定启动文件为根的文件树返回所有文件。
例如,下面是一个文件树:
\---folder
| file1.txt
| file2.txt
|
\---subfolder
file3.txt
file4.txt
使用 java.nio.file.Files.walk(Path)
方法:
Files.walk(Paths.get("folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
给出以下结果:folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt
要获取当前目录中的所有文件,请使用java.nio.file.Files.list(Path)
:
Files.list(Paths.get("folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
结果:
folder\file1.txt
folder\file2.txt
Files.list
的示例点个赞。如果您 不想 递归搜索,这有时可能是最佳选择。 - Per LundbergFiles.list
仅返回文件而不是文件夹。 - FSmimport java.io.File;
public class ReadFilesFromFolder {
public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
static String temp = "";
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
listFilesForFolder(folder);
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
// System.out.println("Reading files under the folder "+folder.getAbsolutePath());
listFilesForFolder(fileEntry);
} else {
if (fileEntry.isFile()) {
temp = fileEntry.getName();
if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
}
}
}
}
}
在Java 7及更高版本中,您可以使用listdir
Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
System.out.println(file.getFileName());
}
} catch (IOException | DirectoryIteratorException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can only be thrown by newDirectoryStream.
System.err.println(x);
}
你也可以创建一个过滤器,然后将其传递给上面的newDirectoryStream
方法
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
public boolean accept(Path file) throws IOException {
try {
return (Files.isRegularFile(path));
} catch (IOException x) {
// Failed to determine if it's a file.
System.err.println(x);
return false;
}
}
};
查看其他筛选示例,请[参阅文档]。(http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob)
private static final String ROOT_FILE_PATH="/";
File f=new File(ROOT_FILE_PATH);
File[] allSubFiles=f.listFiles();
for (File file : allSubFiles) {
if(file.isDirectory())
{
System.out.println(file.getAbsolutePath()+" is directory");
//Steps for directory
}
else
{
System.out.println(file.getAbsolutePath()+" is file");
//steps for files
}
}
只需使用 Files.walkFileTree
(Java 7)遍历所有文件即可。
Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("file: " + file);
return FileVisitResult.CONTINUE;
}
});
C:\
上容易重现。 - Thomas S.如果您想要更多选项,可以使用此函数来填充一个包含文件夹中存在的文件的数组列表。选项包括:递归和匹配模式。
public static ArrayList<File> listFilesForFolder(final File folder,
final boolean recursivity,
final String patternFileFilter) {
// Inputs
boolean filteredFile = false;
// Ouput
final ArrayList<File> output = new ArrayList<File> ();
// Foreach elements
for (final File fileEntry : folder.listFiles()) {
// If this element is a directory, do it recursivly
if (fileEntry.isDirectory()) {
if (recursivity) {
output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter));
}
}
else {
// If there is no pattern, the file is correct
if (patternFileFilter.length() == 0) {
filteredFile = true;
}
// Otherwise we need to filter by pattern
else {
filteredFile = Pattern.matches(patternFileFilter, fileEntry.getName());
}
// If the file has a name which match with the pattern, then add it to the list
if (filteredFile) {
output.add(fileEntry);
}
}
}
return output;
}
最好的,埃德里安
Files.walkFileTree
方法,详见https://dev59.com/PXI-5IYBdhLWcg3wc4Cw#23814217。 - micha