Danny0317
Danny0317

Reputation: 31

Loop to access specific files?

I have 700 files in one folder, each one with a number 1-700, with the file extension .pkmn. I created them and changed their data with a program, but now how would I access them? I've tried a for loop with the path + i + ".pkmn", but it didn't work. How would I access them and assign them to a File?

Thank you.

Upvotes: 0

Views: 88

Answers (2)

Si mo
Si mo

Reputation: 989

You should use the methods of java nio file instead of the "old" io package! It is much faster.

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

https://docs.oracle.com/javase/tutorial/essential/io/dirs.html#listdir

Upvotes: 1

andrucz
andrucz

Reputation: 2021

You can use listFiles() method, that returns an array of files in a directory:

File directory = new File("directory path");
File[] createdFiles = directory.listFiles();
for (File createdFile : createdFiles) {
     ...
}

Upvotes: 1

Related Questions