clojure library code fails to load resource file when called from java

693 views
Skip to first unread message

fenton

unread,
Sep 7, 2012, 1:58:06 PM9/7/12
to clo...@googlegroups.com
https://github.com/ftravers/PublicDocumentation/blob/master/clojure/resource-file.md


Reading a resource file

File/directory layout:

$ tree
.
|-- pom.xml
|-- project.clj
|-- README.md
`-- src
    |-- test_project
    |   `-- Core.clj
    `-- test.txt

Setting up this to be a library for use in Java. Here is my project.clj and my Core.clj

(defproject test-package/test-project "0.1.0-SNAPSHOT"
  :plugins [[lein-swank "1.4.4"]]
  :dependencies [[org.clojure/clojure "1.4.0"]]
  :main test-project.Core)
(ns test-project.Core
  (:gen-class
   :methods [[readFile [] String]]))
(defn read-file []
  (slurp (.getFile (clojure.java.io/resource "test.txt"))))
(defn -readFile [this]
  (read-file))

Now if I try to use this in the REPL

test-project.Core> (read-file)
"abc\n"

Works no problem. However when I try this from Java:

Core c = new Core();
c.readFile();

FileNotFound exception is thrown:

java.io.FileNotFoundException: /home/fenton/.m2/repository/test-package/test-project/0.1.0-SNAPSHOT/test-project-0.1.0-SNAPSHOT.jar!/test.txt (No such file or directory)

Whereas:

InputStream stream =
this.getClass().getClassLoader().getResourceAsStream("test.txt");

Finds the file no problem. So whats the problem?

Dave Ray

unread,
Sep 7, 2012, 2:08:41 PM9/7/12
to clo...@googlegroups.com
slurp is happy to slurp from a URL, no need for the (.getFile) call on
the resource. In other words, the file returned for a resource that's
been compiled into a jar isn't very useful. Stick with the URL
returned bye clojure.java.io/resource.

Dave
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@googlegroups.com
> Note that posts from new members are moderated - please be patient with your
> first post.
> To unsubscribe from this group, send email to
> clojure+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en

fenton

unread,
Sep 7, 2012, 2:30:38 PM9/7/12
to clo...@googlegroups.com
Thanks so much Dave that was it! :)
Reply all
Reply to author
Forward
0 new messages