以下是多种不同的 Java 实现方法来读取文件夹中的文件:
方法一:使用 File 类
import java.io.File;
public class ReadFilesInFolder {
public static void main(String[] args) {
File folder = new File("folderPath");
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
System.out.println(file.getName());
}
}
}
}
}
方法二:使用 Java 8 Stream API
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadFilesInFolder {
public static void main(String[] args) throws IOException {
Path folder = Paths.get("folderPath");
Files.walk(folder)
.filter(Files::isRegularFile)
.forEach(file -> System.out.println(file.getFileName()));
}
}
方法三:使用 Apache Commons IO 库
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
public class ReadFilesInFolder {
public static void main(String[] args) throws IOException {
File folder = new File("folderPath");
Collection<File> files = FileUtils.listFiles(folder, null, false);
for (File file : files) {
System.out.println(file.getName());
}
}
}
标签:file,java,读取,文件夹,File,import,folder,public
From: https://www.cnblogs.com/hefeng2014/p/18357513