ClojureDocs

导航

名称空间

资源

clojure.java.io

1.2 版起可用
  • (resource n)
  • (resource n loader)
Returns the URL for a named resource. Use the context class loader
 if no loader is specified.
2 Examples
; Use clojure.java.io/resource to read resources from the classpath:

(ns rescue.core
  (:require [clojure.java.io :as io] ))

; Populate the file on the command line:  
;   echo "Hello Resources!" > resources/hello.txt
(def data-file (io/resource 
                   "hello.txt" ))
(defn -main []
  (println (slurp data-file)) )
; When do "lein run"
; => Hello Resources!
(require '(clojure.java.io :as io))

;; If the resource does not exist on the classpath a nil is returned.
(io/resource "I_do_not_exist.txt")
;;=> nil
See Also

Opens a reader on f and reads all its contents, returning a string. See clojure.java.io/reader for...

Added by MicahElliott

Attempts to coerce its argument into an open java.io.Reader. Default implementations always retur...

Added by MicahElliott

Returns the lines of text from rdr as a lazy sequence of strings. rdr must implement java.io.Buffe...

Added by MicahElliott
2 Notes
    By , created 9.8 years ago

    If you need to slurp a file from a JAR file, don't call io/file on the result of calling io/resource, or you will get an exception that says the resource is "not a file". Instead, call slurp directly on the result of io/resource.

    By , created 8.8 years ago, updated 8.8 years ago

    If you need to copy a binary file from a running JAR (or WAR), don't call slurp as it will try and decode the file. Instead, extract similarily to:

    (with-open [in (io/input-stream (io/resource "file.dat"))] ;; resources/file.dat
        (io/copy in (io/file "/path/to/extract/file.dat"))))