Loading...
Logo
Processing Forum

Filename filtering

in Programming Questions  •  3 years ago  
I would like my sketch to parse some text files in a subfolder to the sketches data folder, or perhaps in arbitrary folder. However, on a mac, the OS always creates a file called ".DS_Store". I would like my sketch to only read files that have a .txt extension. In general i would like to know how to code sketches that can use arbitrary file filters. Unfortunately the JavaDoc regarding the FileFilter interface is a bit over my head, and the processing.org documentation on file i/o is sparse. Any help or code snippets would be greatly appreciated!

Replies(1)

So after some googling and cut-pasting, I was able to cobble this together. I have to admit that I don't really 'get' it, but it works. I suspect I'll have to study up on Java File i/o to grok what's going on here.

Copy code
  1. String[] fileNames;

  2. // let's set a filter (which returns true if file's extension is .jpg)
  3. java.io.FilenameFilter txtFilter = new java.io.FilenameFilter() {
  4.   boolean accept(File dir, String name) {
  5.     return name.toLowerCase().endsWith(".txt");
  6.   }
  7. };

  8. void setup() {

  9.   println("the sketch path is "+sketchPath);
  10.   String folderPath = selectFolder();
  11.   if (folderPath == null) {
  12.     // If a folder was not selected
  13.     println("No folder was selected...");
  14.   } 
  15.   else {
  16.     // If a folder was selected, print path to folder
  17.     println(folderPath);
  18.     fileNames = listFileNames(folderPath, txtFilter);
  19.     println(fileNames);
  20.   }
  21. }

  22. // This function returns all the files in a directory as an array of Strings  
  23. String[] listFileNames(String dir,java.io.FilenameFilter extension) {
  24.   
  25.   File file = new File(dir);
  26.   if (file.isDirectory()) {
  27.     String names[] = file.list(extension);
  28.     return names;
  29.   } else {
  30.     // If it's not a directory
  31.     return null;
  32.   }
  33. }