0

I want to be able to count all the save games a user has created.

Using Java, how can I count all the files in a directory with a specific extension?

This code counts all the files regardless of extension:

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();
        }
    }
}
LuminousNutria
  • 1,883
  • 2
  • 18
  • 44

3 Answers3

1

Pass your extension in this function.

amountOfFiles = files.map(Path::toFile).filter(e->e.getName().endsWith(".xml")).count();
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
0

I have managed to figure it out on my own. Since I couldn't figure out how to use the Path endsWith() method, I had to convert each Path object to a String, and then use the String version of the endsWith() method instead.

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();
    }
}
LuminousNutria
  • 1,883
  • 2
  • 18
  • 44
0

You can use FilenameFilter and FileFilter to filter you needed file or dirctory.

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());

You can refer to the official documentation Java IO

TongChen
  • 1,414
  • 1
  • 11
  • 21