loadImage only if file exist

According to loadImage()'s reference:

It simply returns null when it fails:

If the file is not available or an error occurs, null will be returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned is null.

Let’s say you’ve got an ArrayList to store all your loaded images:

import java.util.List;
final List<PImage> images = new ArrayList<PImage>();

Then you could just check for null before add() each PImage:

PImage img;

for (final String url : loadStrings("urls.txt"))
  if ((img = loadImage(url)) != null)  images.add(img);

If that’s so the previous loop can be adapted like this:

final String url = "https://SiteName/FolderName/", name = "image", ext = ".jpg";
PImage img;
int i = 0;

while (++i <= 10000)
  if ((img = loadImage(url + name + i + ext)) != null)  images.add(img);
5 Likes