Listing files tutorial not working?

edited March 2014 in Questions about Code

Hey I was hoping to use this jpg file listing tutorial in my program, but it doesn't seem to work- does anyone know how to fix it? http://wiki.processing.org/w/Listing_files

Rigth now, it's giving a NullPointerException here-

println(filenames.length + " jpg files in specified directory");

which I have figured means that filenames is probably not well declared. Or can't be read or something. I suspect it's because folder.list() is not really a thing- the reference seems to indicate it's only for fonts. Is it because the tutorial is old? Is there a way to update it?

Andddd once that's been figured out, is there a way to make it read any folder and not just the data one from the sketch (which I assume is what it does)?

Thanks so much for any tips on how to make this work!!!

(In case you're interested, I'm going to use it to display a bunch of images without having to write the name of each file in the code)

Answers

  • edited March 2014 Answer ✓

    You first need to specify the path to the directory. If it is empty you get NullPointerException. To list all the folders you need a new filter that has isDirectory() inside. Then list() the folder path. Also note that the path has "/" instead of "\". The second one is for ignoring characters in a string. Here is the example

    // The data path of the folder to look in (write your own)
    java.io.File folder = new java.io.File(dataPath("C:/Users/Username/Desktop/sketchName"));
    
    // let's set a filter (which returns true if file's extension is .jpg)
    java.io.FilenameFilter jpgFilter = new java.io.FilenameFilter() {
      boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".jpg");
      }
    };
    
    // list all the folders inside the main directory
    String[] listFolders = folder.list(new java.io.FilenameFilter() {
      public boolean accept(File current, String name) {
        return new File(current, name).isDirectory();
      }
    });
    
    // list the files in the data folder, passing the filter as parameter
    String[] filenames = folder.list(jpgFilter);
    String[] foldernames = folder.list();
    
    // get and display the number of jpg files
    println(filenames.length + " jpg files in specified directory");
    println(foldernames.length -1 + " folders in the specified directory");
    
    // display the folder names
    for(int i=0; i < foldernames.length-1; i++) {
      println(listFolders[i]);
    }
    
    // display the filenames
    for (int i = 0; i < filenames.length; i++) {
      println(filenames[i]);
    }
    
  • edited March 2014

    Oh dear. Just adding something in the directory path. That was easy. Thanks ;;) It's kinda silly because I thought of doing it but then I got some weird errors because I didn't know about backslashes. The more you know...

Sign In or Register to comment.