views:

94

answers:

1

Hi

I call a java function in Clojure to get a list of files.

(require '[clojure.java.io :as io])
(str (.listFiles (io/file "/home/loluser/loldir")))

And I get a whole bunch of strings like these

#<File /home/loluser/loldir/lolfile1>

etc. How do I get rid of the brackets and put them in some form of an array so another function can access it?

+7  A: 

Those strings are just the print format for a Java File object.

See the File javadoc for which operations are available.

If you want the file paths as strings, it would be something like

(map #(.getPath %) 
  (.listFiles (io/file "/home/loluser/loldir")))

Or you could just use list, which returns strings in the first place:

(.list (io/file "/home/loluser/loldir"))

If you want to read the file, you might as well keep it as a File object to pass into the core slurp or other clojure.java.io or clojure.contrib.duck-streams functions.

j-g-faustus
Could I pass the File object to slurp like this: (slurp (first (.listFiles (io/file "/home/loluser/loldir")))) or maybe put it into a var first and then do a slurp of the var?
bleakgadfly
Yes. Although listFiles returns both files and directories, so you would probably want to filter with #(.isFile %) first.
j-g-faustus
As an aside, note the mangled syntax highlighting.
Svante
@j-g-faustus: Is there a way to sort the files in the map by lastModified date?
bleakgadfly
Sure: `(sort-by #(.lastModified %) (.listFiles (io/file "/etc")))` http://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/sort-by
j-g-faustus