HIDE NAV

Resource File Listing & Loading in a Loop

The below command line program demonstrates how to query the contents of resources subdirectories and list all files in those directories

Main.java


package ceccs;

import java.io.File;
import java.net.URLDecoder;

public class Main {

    public static void main(String[] args) {
        //build a list of images
        try {
            //first create a string for the path so we can decode it
            //URLDecoder is necessary because spaces are swapped for %20 in URIs
            //Also Note from non-static method you can use getClass().getResource()...
            String imgDirPath = Main.class.getResource("/images and photos").getFile();
            imgDirPath = URLDecoder.decode(imgDirPath, "UTF-8");
            File imgDir = new File(imgDirPath);
            System.out.println("imgFile Path:  " + imgDir);
            String[] imgFiles = imgDir.list();
            for (int i = 0; i < imgFiles.length; i++) {
                String uriPath = imgDir.toURI() + "/" + imgFiles[i];
                System.out.println(uriPath);
                String rawTextPath = imgDirPath + "/" + imgFiles[i];
                System.out.println(rawTextPath);
            }
            //Note: you may have to reconstruct the file path or re-convert to
            // URIs to load the images into your graphics library
        } catch(Exception ex){
            System.out.println(ex);
        }

        //build a list of sounds
        try {
            String soundDirPath = Main.class.getResource("/sounds").getFile();
            soundDirPath = URLDecoder.decode(soundDirPath, "UTF-8");
            File soundDir = new File(soundDirPath);
            System.out.println("soundFile Path:  " + soundDir);
            String[] soundFiles = soundDir.list();
            for (int i = 0; i < soundFiles.length; i++) {
                System.out.println(soundFiles[i]);
            }
        } catch(Exception ex){
            System.out.println(ex);
        }
    }
}