Loading a resource file from the class path?

430 views
Skip to first unread message

Darren Austin

unread,
Dec 20, 2008, 6:12:30 AM12/20/08
to clo...@googlegroups.com
Hey folks,

I am probably missing something obvious here, but is there an good way
to open a resource file that is relative to the current class path? I
want to bundle up some data files with my .clj source in a .jar file.
From the clojure code, I need to open these data files. I looked at
Class.getResourceAsStream(), but I couldn't find a good way to get an
object that would give me a Class object from the package/ns of my
clojure code. Any suggestions on how to achieve this?

Thanks,
--Darren

Mike DeLaurentis

unread,
Dec 20, 2008, 7:59:08 AM12/20/08
to clo...@googlegroups.com
I've never done that in Clojure, but another developer at the company
I work for made a java utility that allows you to refer to classpath
resources as URLs. It's on sourceforge in a package called "OpenHMS
Common Utilities":

http://openhms.sourceforge.net/common-util/

There's a class called
com.healthmarketscience.common.util.resource.Handler that, when
initialized, registers a "resource" URL handler. I think you should be
able to do something like:

;; Call the static init method on the Handler class to register the
resource: URL handler.
;; You just need to do this once before trying to use a resource URL
(. com.healthmarketscience.common.util.resource.Handler init)

;; Use resource:... URLs just like any other
(.openStream (new URL "resource:the/classpath/resource.txt"))

I use this in java code all the time. I've never tried it in Clojure,
but there's no reason it shouldn't work.

If you decide not to use that, then try something like:

(.findResource (.getContextClassLoader (.currentThread Thread))
"your.resource.txt")

blackdog

unread,
Dec 20, 2008, 8:44:58 AM12/20/08
to clo...@googlegroups.com
here's something ...

(defn loadTextResource [path]
(let [bl (.baseLoader clojure.lang.RT)
inps (.getResourceAsStream bl path)]
(if inps
(with-open [r (BufferedReader.
(InputStreamReader. inps))] (let [sb (new StringBuilder)]
(loop [c (. r (read))]
(if (neg? c)
(str sb)
(do
(. sb
(append (char c))) (recur (. r (read))))))))

--
None are more hopelessly enslaved than those who falsely believe they
are free — Goethe
Reply all
Reply to author
Forward
0 new messages