在Java中,如何统计一个目录中具有相同文件扩展名的文件个数?
How to count the number of files in a directory, with the same file extension, in Java?
我希望能够统计一个用户创建的所有游戏存档。
使用Java,如何计算一个目录中具有特定扩展名的所有文件?
此代码计算所有文件,无论扩展名如何:
public class MCVE {
public static void main(String[] args) {
countFiles();
}
private static void countFiles() {
long amountOfFiles = 0;
try {
Stream<Path> files = Files.list(Paths.get("./saves"));
amountOfFiles = files.count();
System.out.println(amountOfFiles);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在此函数中传递您的扩展名。
amountOfFiles = files.map(Path::toFile).filter(e->e.getName().endsWith(".xml")).count();
我已经设法自己解决了。由于我不知道如何使用 Path endsWith()
方法,我不得不将每个 Path 对象转换为 String,然后改用 endsWith()
方法的 String 版本。
private static void countFiles() {
long amountOfFiles = 0;
try {
Stream<Path> files = Files.list(Paths.get("./saves"));
Iterable<Path> iterable = files::iterator;
String fileName = "";
for (Path p: iterable) {
fileName = p.getFileName().toString();
if(fileName.endsWith(".sav"))
amountOfFiles++;
}
System.out.println(amountOfFiles);
files.close();
} catch (IOException e) {
e.printStackTrace();
}
}
您可以使用FilenameFilter
和FileFilter
来过滤您需要的文件或目录。
File file = new File("pathname");
// fileter file name start wit Chap
file.listFiles(pathname -> pathname.getName().startsWith("Chap"));
// fileter car read file
file.listFiles(pathname -> pathname.canRead());
可以参考官方文档Java IO
我希望能够统计一个用户创建的所有游戏存档。
使用Java,如何计算一个目录中具有特定扩展名的所有文件?
此代码计算所有文件,无论扩展名如何:
public class MCVE {
public static void main(String[] args) {
countFiles();
}
private static void countFiles() {
long amountOfFiles = 0;
try {
Stream<Path> files = Files.list(Paths.get("./saves"));
amountOfFiles = files.count();
System.out.println(amountOfFiles);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在此函数中传递您的扩展名。
amountOfFiles = files.map(Path::toFile).filter(e->e.getName().endsWith(".xml")).count();
我已经设法自己解决了。由于我不知道如何使用 Path endsWith()
方法,我不得不将每个 Path 对象转换为 String,然后改用 endsWith()
方法的 String 版本。
private static void countFiles() {
long amountOfFiles = 0;
try {
Stream<Path> files = Files.list(Paths.get("./saves"));
Iterable<Path> iterable = files::iterator;
String fileName = "";
for (Path p: iterable) {
fileName = p.getFileName().toString();
if(fileName.endsWith(".sav"))
amountOfFiles++;
}
System.out.println(amountOfFiles);
files.close();
} catch (IOException e) {
e.printStackTrace();
}
}
您可以使用FilenameFilter
和FileFilter
来过滤您需要的文件或目录。
File file = new File("pathname");
// fileter file name start wit Chap
file.listFiles(pathname -> pathname.getName().startsWith("Chap"));
// fileter car read file
file.listFiles(pathname -> pathname.canRead());
可以参考官方文档Java IO