'Clojure list subfolders in resources in uberjar

I have a folder structure like this:

  • resources
    • a
      • b
        • x.txt
      • c
        • x.txt

I've created my runnable jar with lein uberjar.

When running my jar, I want to list the subfolders of a.

I know I can get the contents of resources/a/b/x.txt using clojure.java.io

(slurp (clojure.java.io/resource "a/b/x.txt"))

But I can't find a simple way to list the subfolders.

(clojure.java.io/file (clojure.java.io/resource "a")) just results in a java.lang.IllegalArgumentException: Not a file because it isn't a file, it's a resource inside the jar file.

Is there a library that does this?



Solution 1:[1]

A different approach (but I must admit that it doesn't feel entirely satisfactory) is to read the contents at compile time. Assuming you have a function list-files that gives you the list from your project root directory:

(defmacro compile-time-filelist []
  `'~(list-files "resources/a"))

or

(defmacro compile-time-filelist []
  (vec (list-files "resources/a")))

Solution 2:[2]

You can recursively list all items in a dir using file-seq function. Example:

(let [files (file-seq (clojure.java.io/file "resources"))
      dir? #(.isDirectory %)]
  (map dir? files))

You can also call .listFiles or .list on a File object. The first gives file objects, the second gives filenames.

You can find additional examples here and here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Svante
Solution 2 Herman Nurlygayanov