Compojure: access filesystem

2019-05-11 17:50发布

问题:

this is my project.clj file:

(defproject org.github.pistacchio.deviantchecker "0.9.0"
  :description "A one page application for keeping track of changes on deviantart.com gallieries"
  :dependencies [[org.clojure/clojure "1.2.1"]
                 [org.clojure/clojure-contrib "1.2.0"]
                 [enlive  "1.0.0"]
                 [compojure "0.6.4"]
                 [ring/ring-jetty-adapter "1.0.0-beta2"]]
  :dev-dependencies [[lein-ring "0.4.6"]]
  :ring {:handler org.github.pistacchio.deviantchecker.core/app}
  :main org.github.pistacchio.deviantchecker.core)

and this my routing:

(defroutes main-routes
  (GET "/" [] (get-home))
  (GET "/add" [d] (add-gallery d))
  (GET "/delete" [d] (delete-gallery d))
  (GET "/check" [d] (check-gallery d))
  (route/resources "/")
  (route/not-found "Page not found"))

I have some web static files in /resources/public and I can access them. In the code I also need o access some files on the file system that are located on /resources/data and /resources/tpl. Using lein ring server or lein run, the following call works fine

(java.io.File. "resources/tpl/home.html")

but when packing the application with lein uberwar and deploying under Tomcat it fails and I get a FileNotFoundException. Maybe this is because with lein the current working directory is the project root while under Tomcat it is Tomcat's bin directory.

For example, I have /resources/data/data.dat that gets packed in the war as /data/data.dat so either "resources/data/data.dat" doesn't work under Tomcat or "data/data.dat" doesn't work in development.

By the way, what is the proper way of managing this in Compojure? Thanks.

回答1:

You can use clojure.java.io/resource to access resources whether they're on the local file system, or packed in a jar/war:

(require '[clojure.java.io :as io])
(io/reader (io/resource "public/some/file.txt")) ; file in resource classpath or $root/resources/public...

You probably shouldn't try to load them from a directory, since you can't be sure where the file is going to end up when its deployed from a jar/war (or even if it's on the file system at all, probably).