# File Listing Order

**URL:** <https://discourse.processing.org/t/file-listing-order/7148>\
**Category:** Coding Questions\
**Created:** [January 4, 2019, 4:43am UTC](https://discourse.processing.org/t/file-listing-order/7148 "2019-01-04T04:43:52Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![philspitler](https://avatars.discourse-cdn.com/v4/letter/p/f1d935/32.png) [@philspitler](https://discourse.processing.org/u/philspitler)\
**Post date:** [January 4, 2019, 4:43am UTC](https://discourse.processing.org/t/file-listing-order/7148/1 "2019-01-04T04:43:52Z")

</div>

Hi, I’m curious how Processing decides the order of files in a directory listing and if there is a way to sort alphabetical.

I’m using the sample code below and the listing doesn’t seem to be alphabetical or by date modified.

I need to loop through a few thousand images that are in subfolders, the subfolders are alphabetical and I want to keep my list that way.

Any ideas?

```auto
import java.util.Date;

void setup() {

  // Using just the path of this sketch to demonstrate,
  // but you can list any directory you like.
  String path = "/Users/philspitler/Desktop/";

  println("\nListing info about all files in a directory and all subdirectories: ");
ArrayList<File> allFiles = listFilesRecursive(path);
 

  for (File f : allFiles) {
   
    println("Full path: " + f.getAbsolutePath());
 
  }

  noLoop();
}

// Nothing is drawn in this program and the draw() doesn't loop because
// of the noLoop() in setup()
void draw() {
}

// Function to get a list of all files in a directory and all subdirectories
ArrayList<File> listFilesRecursive(String dir) {
  ArrayList<File> fileList = new ArrayList<File>(); 
  recurseDir(fileList, dir);
  return fileList;
}

// Recursive function to traverse subdirectories
void recurseDir(ArrayList<File> a, String dir) {
  File file = new File(dir);
  if (file.isDirectory()) {
    // If you want to include directories in the list
    a.add(file);  
    File[] subfiles = file.listFiles();
    for (int i = 0; i < subfiles.length; i++) {
      // Call this function on all files in this directory
      recurseDir(a, subfiles[i].getAbsolutePath());
    }
  } else {
    a.add(file);
  }
}

```

---

<div class="post-metadata">

**Author:** ![Architector\_4](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/architector_4/32/813_2.png) [@Architector\_4](https://discourse.processing.org/u/Architector_4)\
**Post date:** [January 4, 2019, 5:18am UTC](https://discourse.processing.org/t/file-listing-order/7148/2 "2019-01-04T05:18:36Z")

</div>

Since Processing is based on Java, and you are pretty much using only Java functions everywhere, I looked for _“Java change sort of File.listFiles();”_ and found that you can use `Arrays.sort(subfiles);` to sort array `subfiles`. However you would need to import `java.util.Arrays` to do the thing above - or you can use `java.util.Arrays.sort(subfiles);` instead.

So, this changes your `recurseDir` function to:

```auto
void recurseDir(ArrayList<File> a, String dir) {
  File file = new File(dir);
  if (file.isDirectory()) {
    // If you want to include directories in the list
    a.add(file);  
    File[] subfiles = file.listFiles();
    java.util.Arrays.sort(subfiles); //Sorts all files by name
    for (int i = 0; i < subfiles.length; i++) {
      // Call this function on all files in this directory
      recurseDir(a, subfiles[i].getAbsolutePath());
    }
  } else {
    a.add(file);
  }
}

```

I suggest looking for answers related to Java in the internet, as Processing is pretty much a wrapper for it and Java is more documented than Processing.

P.S. I also suggest using `exit();` instead of `noLoop();` to close the sketch as soon as it’s done.

---

<div class="post-metadata">

**Author:** ![philspitler](https://avatars.discourse-cdn.com/v4/letter/p/f1d935/32.png) [@philspitler](https://discourse.processing.org/u/philspitler)\
**Post date:** [January 4, 2019, 5:22am UTC](https://discourse.processing.org/t/file-listing-order/7148/3 "2019-01-04T05:22:54Z")

</div>

Wow, thanks for the quick reply, this seems to be exactly what I need.

Thanks.

Phil

---

<div class="post-metadata">

**Author:** ![kll](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kll/32/964_2.png) [@kll](https://discourse.processing.org/u/kll)\
**Post date:** [January 4, 2019, 5:32am UTC](https://discourse.processing.org/t/file-listing-order/7148/4 "2019-01-04T05:32:57Z")

</div>

a file type selector “\*.img” might be also nice??

---

<div class="post-metadata">

**Author:** ![Architector\_4](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/architector_4/32/813_2.png) [@Architector\_4](https://discourse.processing.org/u/Architector_4)\
**Post date:** [January 4, 2019, 8:04am UTC](https://discourse.processing.org/t/file-listing-order/7148/5 "2019-01-04T08:04:37Z")

</div>

That could actually be useful, too. Here, the same function above, but with a file extension check added:

```auto
void recurseDir(ArrayList<File> a, String dir) {
  File file = new File(dir);
  if (file.isDirectory()) {
    // If you want to include directories in the list
    a.add(file);  
    File[] subfiles = file.listFiles();
    java.util.Arrays.sort(subfiles); //Sorts all files by name
    for (int i = 0; i < subfiles.length; i++) {
      // Call this function on all files in this directory
      recurseDir(a, subfiles[i].getAbsolutePath());
    }
  } else {
    String fileName = file.getName();
    if(
      //fileName.endsWith(".other-random-formats")||
      fileName.endsWith(".gif")||
      fileName.endsWith(".jpg")||
      fileName.endsWith(".jpeg")||
      fileName.endsWith(".tga")||
      fileName.endsWith(".png")
    ) {
      a.add(file);
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![kll](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kll/32/964_2.png) [@kll](https://discourse.processing.org/u/kll)\
**Post date:** [January 4, 2019, 9:01am UTC](https://discourse.processing.org/t/file-listing-order/7148/6 "2019-01-04T09:01:04Z")

</div>

some rearrangement

```auto
// https://discourse.processing.org/t/file-listing-order/7148
// @philspitler @Architector_4

ArrayList<File> myfiles;
String path = "/home/pi/projects/processing/sketchbook";
boolean piconly = true;

void setup() {
  println("\nListing info about all files in a directory and all subdirectories \n _filter_ piconly: "+piconly);
  myfiles = listFilesRecursive(path,piconly);
  for (File afile : myfiles) println("File: "+afile ); // afile.getAbsolutePath());
}

void draw() {
}

// Function to get a list of all files in a directory and all subdirectories // with piconly filter
ArrayList<File> listFilesRecursive(String dir,boolean piconly) {
  ArrayList<File> fileList = new ArrayList<File>(); 
  recurseDir(fileList, dir, piconly); // ( file array , root_directory , pictures only )
  return fileList;
}

// Recursive function to traverse subdirectories
void recurseDir(ArrayList<File> a, String dir, boolean piconly) {
  boolean showdirs = false;
  File file = new File(dir);
  if (file.isDirectory()) {
    if ( showdirs ) a.add(file); // only if you want to include directories in the list
    File[] subfiles = file.listFiles();
    java.util.Arrays.sort(subfiles); //Sorts all files by name
    for (int i = 0; i < subfiles.length; i++) recurseDir(a, subfiles[i].getAbsolutePath(), piconly ); // Call this function on all files in this directory
  } else {
    String fileName = file.getName();
    if ( piconly ) {
    if ( //fileName.endsWith(".other-random-formats")||
      fileName.endsWith(".gif") ||
      fileName.endsWith(".jpg") ||
      fileName.endsWith(".jpeg") ||
      fileName.endsWith(".tga") ||
      fileName.endsWith(".png") ||
      fileName.endsWith(".svg") 
      ) a.add(file); // if picture for piconly
    } else { a.add(file); } // all
  }
}

```

---

<div class="post-metadata">

**Author:** ![Architector\_4](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/architector_4/32/813_2.png) [@Architector\_4](https://discourse.processing.org/u/Architector_4)\
**Post date:** [January 4, 2019, 9:43am UTC](https://discourse.processing.org/t/file-listing-order/7148/7 "2019-01-04T09:43:36Z")

</div>

Why so picky?? 😶

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [January 4, 2019, 10:42am UTC](https://discourse.processing.org/t/file-listing-order/7148/8 "2019-01-04T10:42:26Z")

</div>

**listPaths()**:

> [@How to check if a file is exist in data folder by code?](https://discourse.processing.org/t/how-to-check-if-a-file-is-exist-in-data-folder-by-code/589/7):
>
> Yes! Just pass an empty string "" to dataPath(): dataFolderPath = this.dataPath('') + '/' print dataFolderPath … or to dataFile(): dir = this.dataFile('') dataFolderPath = dir.path + '/' print dataFolderPath However, if you need all files within the sketch’s “data/” folder, like all images for example, you can use listPaths(), passing the “data/” folder path + a string w/ all desired “extensions=,”: sunglasses PICS\_EXTS = 'extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp,wbmp' dir = this.…

---

<div class="post-metadata">

**Author:** ![Architector\_4](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/architector_4/32/813_2.png) [@Architector\_4](https://discourse.processing.org/u/Architector_4)\
**Post date:** [January 4, 2019, 10:59am UTC](https://discourse.processing.org/t/file-listing-order/7148/9 "2019-01-04T10:59:46Z")

</div>

Isn’t that for Python?  
That function seems to exist in Java too, but what is the correct usage? Is it different from Python? It doesn’t seem to be documented anywhere, too.  
Besides, does it return paths in alphabetical order?

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [January 4, 2019, 11:27am UTC](https://discourse.processing.org/t/file-listing-order/7148/10 "2019-01-04T11:27:10Z")

</div>

> [@Architector\_4](#):
>
> Isn’t that for Python?

It’s under Python Mode (Jython) forum category. 🐍

> [@Architector\_4](#):
>
> That function seems to exist in Java too,

It’s a method belonging to Processing’s PApplet class: ☕

[Processing.GitHub.io/processing-javadocs/everything/processing/core/PApplet.html#listPaths-java.lang.String-java.lang.String...-](http://Processing.GitHub.io/processing-javadocs/everything/processing/core/PApplet.html#listPaths-java.lang.String-java.lang.String%2E%2E%2E-)

> [@Architector\_4](#):
>
> Is it different from Python?

It’s not that hard to convert it to Java Mode: 🙃

```java
final String PICS_EXTS = "extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp,wbmp";

final File dir = dataFile("");

String[] imagePaths = {};
int imagesFound = 0;

if (dir.isDirectory()) {
  imagePaths = listPaths(dir.getPath(), "files", "recursive", PICS_EXTS);
  imagesFound = imagePaths.length;
}

printArray(imagePaths);
println("Found", imagesFound, "image(s)");

exit();

```

```python
PICS_EXTS = 'extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp,wbmp'

dir = this.dataFile('')
imagePaths, imagesFound = (), 0

if dir.isDirectory():
    imagePaths = this.listPaths(dir.path, 'files', 'recursive', PICS_EXTS)
    imagesFound = len(imagePaths)

printArray(imagePaths)
print 'Found %d image(s)' % imagesFound

exit()

```

> [@Architector\_4](#):
>
> Besides, does it return paths in alphabetical order?

Given **listPaths()** returns an array of strings (String[]), it’s easily sortable by Arrays::**sort()**: 📁

[Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object[])](http://Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D))

---

<div class="post-metadata">

**Author:** ![Architector\_4](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/architector_4/32/813_2.png) [@Architector\_4](https://discourse.processing.org/u/Architector_4)\
**Post date:** [January 4, 2019, 12:32pm UTC](https://discourse.processing.org/t/file-listing-order/7148/11 "2019-01-04T12:32:24Z")

</div>

Hmm. I guess this then allows to change their `listFilesRecursive()` function to this:

```auto
final String PICS_EXTS = "extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp,wbmp";

String[] listFilesRecursive(String dir) {
  String[] result = listPaths(dir, PICS_EXTS);
  sort(result);
  return result;
}

```

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [January 4, 2019, 12:41pm UTC](https://discourse.processing.org/t/file-listing-order/7148/12 "2019-01-04T12:41:06Z")

</div>

> [@Architector\_4](#):
>
> `File[] result = listPaths(dir, PICS_EXTS);`

As stated, **listPaths()** returns a String[]. For File[], go w/ **listFiles()** instead:

[Processing.GitHub.io/processing-javadocs/everything/processing/core/PApplet.html#listFiles-java.lang.String-java.lang.String...-](http://Processing.GitHub.io/processing-javadocs/everything/processing/core/PApplet.html#listFiles-java.lang.String-java.lang.String%2E%2E%2E-)

> [@Architector\_4](#):
>
> `final String PICS_EXTS = "extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp,wbmp";`

Those are all files extensions that **loadImage()** recognizes AFAIK.  
We can trim it for a subset of it we actually need for a faster listing.

---

<div class="post-metadata">

**Author:** ![Architector\_4](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/architector_4/32/813_2.png) [@Architector\_4](https://discourse.processing.org/u/Architector_4)\
**Post date:** [January 4, 2019, 12:42pm UTC](https://discourse.processing.org/t/file-listing-order/7148/13 "2019-01-04T12:42:38Z")

</div>

> [@GoToLoop](#):
>
> As stated, **listPaths()** returns a String.

Whoops! Fixed that one.

---

<div class="post-metadata">

**Author:** ![kll](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kll/32/964_2.png) [@kll](https://discourse.processing.org/u/kll)\
**Post date:** [January 4, 2019, 1:24pm UTC](https://discourse.processing.org/t/file-listing-order/7148/14 "2019-01-04T13:24:43Z")

</div>

with this options we get our prior list again:

```auto
String[] myfiles = {};
final String PICS_EXTS = "extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp,wbmp";
//final File dir = dataFile(""); // not work here on linux RASPBIAN println(dir); shows: null/data
final File mydir = dataFile("/home/pi/projects/processing/sketchbook");

void setup() {
  
  println("check: "+mydir+" on files with "+PICS_EXTS);
  if ( mydir.isDirectory() ) myfiles = listPaths(mydir.getPath(), "recursive", "files", PICS_EXTS);
  printArray(myfiles);
}

```

---

<div class="post-metadata">

**Author:** ![Architector\_4](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/architector_4/32/813_2.png) [@Architector\_4](https://discourse.processing.org/u/Architector_4)\
**Post date:** [January 4, 2019, 1:35pm UTC](https://discourse.processing.org/t/file-listing-order/7148/15 "2019-01-04T13:35:57Z")

</div>

Hold on, why do we check if a directory `.isDirectory()` if we know that it’s directory? The only way `mydir` can be a directory is only if someone changes its value in the source code, and if they can do that they can deal with the error themselves!  
This leaves us with no reason to define `mydir` as `File` and with `dataFile(...`, considering we only use it for `mydir.getPath()`…  
Then, why bother with making `String[] myfiles`?  
I guess it makes sense to leave other `String`s as variables to allow for easier change…  
And, why bother putting a full path into `dataPath(...)`?  
😯

```auto
final String PICS_EXTS = "extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp,wbmp";
final String mydir = dataPath(""); // kll, please run this only after settings() :v

void setup() {
  printArray(listPaths(mydir, "recursive", "files", PICS_EXTS));
}

```

Anyways, guys, the solution is found, why bother with needless improvements? 😃

---

<div class="post-metadata">

**Author:** ![kll](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kll/32/964_2.png) [@kll](https://discourse.processing.org/u/kll)\
**Post date:** [January 4, 2019, 1:58pm UTC](https://discourse.processing.org/t/file-listing-order/7148/16 "2019-01-04T13:58:42Z")

</div>

`final File dir = dataFile("");`

not work for me on RASPBIAN and WIN 7

(SOLVED) see [File Listing Order](https://discourse.processing.org/t/file-listing-order/7148/21)

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [January 4, 2019, 2:01pm UTC](https://discourse.processing.org/t/file-listing-order/7148/17 "2019-01-04T14:01:48Z")

</div>

> [@Architector\_4](#):
>
> Hold on, why do we check if a directory `.isDirectory()` if we know that it’s a directory?

From the original forum question:

> [@How to check if a file is exist in data folder by code?](https://discourse.processing.org/t/how-to-check-if-a-file-is-exist-in-data-folder-by-code/589):
>
> I have to check if a file is exist in data folder while the code is running. How to achieve that function?

The `if dir.isDirectory():` check block was intended to assure 1st whether the sketch’s “data/” folder already existed before proceeding any further. 😳

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [January 4, 2019, 2:08pm UTC](https://discourse.processing.org/t/file-listing-order/7148/18 "2019-01-04T14:08:05Z")

</div>

> [@kll](#):
>
> not work for me on RASPBIAN and WIN 7

Although my current laptop is Win 8.1, my previous 1 was Win 7.

And I’m pretty sure both **dataPath()** & **dataFile()** work for all Windows versions!

Notice though that neither subfolders “data/” nor “code/” are created when a sketch project folder is 1st created.

Either we create them by ourselves or they’re created automatically when we drag & drop files into the PDE.

---

<div class="post-metadata">

**Author:** ![kll](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kll/32/964_2.png) [@kll](https://discourse.processing.org/u/kll)\
**Post date:** [January 4, 2019, 2:15pm UTC](https://discourse.processing.org/t/file-listing-order/7148/19 "2019-01-04T14:15:27Z")

</div>

yes, made /data  
copy in some pictures  
tested on Raspberry Pi RASPBIAN and WIN 7  
restarted Processing 3.4

 ![snap_0005](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/9/93d993bb41d177a9e240d149d3d5bbcab2500fa7.jpeg)

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [January 4, 2019, 2:24pm UTC](https://discourse.processing.org/t/file-listing-order/7148/20 "2019-01-04T14:24:01Z")

</div>

Your sketch is buggy! You’re calling **dataFile()** before **settings()**! 🐛  
The `private` system field PApplet::_sketchPath_ is initialized just before **settings()** is called back btW. 📲

[Processing.GitHub.io/processing-javadocs/core/processing/core/PApplet.html#sketchPath--](http://Processing.GitHub.io/processing-javadocs/core/processing/core/PApplet.html#sketchPath--)

[Next page](https://discourse.processing.org/t/file-listing-order/7148.md?page=2)
