How can I count the number of files in a directory?

I’m working on a little side-project where it is necessary for me to preload several images as an array before the rest of the program runs. When this program is run in context, I won’t have any way of knowing how many images are being fed into the array, so I setup the loading in a for loop.

The problem is, I do not know how many images could be in the folder, so I need a way of counting the number of files in the directory. I also won’t be able to know the names of the images, so the code needs to figure out the names of the files.

My current code only can handle a set number of images using a simple naming convention:

// create variables to hold images and songs
var img = [];

// preload the necessary assets
function preload() {

	// preload all the images as an array
	for (i = 0; i < 4; i++) {
		img[i] = loadImage('assets/poss/poss' + i + '.png');
    }

}
public File[] listFiles(String dir) {
  File file = new File(dir);
  if (file.isDirectory()) {
    File[] files = file.listFiles();
    return files;
  } else {
    // If it's not a directory
    return null;
  }
};

https://processing.org/examples/directorylist.html

I think the original question is in p5.js while this solution is for processing. Unfortunately p5.js is “front-end” which does not have access to folders. You may need to use tools like node.js or electron to read local files, or create a metadata in advance, let’s say a json file that has a list of files in the folder, so that the p5.js script first loads the json and then look for all the files from the list.

2 Likes