-1

Closest thing I found was: How do I create a Java string from the contents of a file? I've used this, looking for line breaks and using a while hasNext() loop, but I was wondering if there is an equivalent for image files? I would want to add images from a folder up to a point or until all images are added

Community
  • 1
  • 1
Legato
  • 609
  • 17
  • 24

1 Answers1

2

To list the contents of a directory, you could start with...

File[] contents = new File("/path/to/images").listFiles();

You would now simply need to iterate over the list to determine how to handle each File individually...

Now, you can save yourself some time and supply a FileFilter which will allow you to pre-emptively discard files which you may not be interested in...

File[] contents = new File("path").listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        String name = pathname.getName().toLowerCase();
        return name.endsWith(".png")
                || name.endsWith(".jpg")
                || name.endsWith(".jpeg")
                || name.endsWith(".gif")
                || name.endsWith(".bmp");
    }
});

Once you have the list of image files, you need to iterate the list

for (File imageFile : contents) {
    // Deal with the file...
}

Have a look at java.io.File for more details

Equally, you could use the new Files API...

try {
    final Path master = new File("C:\\Users\\shane\\Dropbox\\MegaTokyo").toPath();
    Files.walkFileTree(master, new FileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return dir.equals(master) ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println(file);
            // Process the file result here
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }
    });
} catch (IOException exp) {
    exp.printStackTrace();
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366