(input-stream x & opts)
Attempts to coerce its argument into an open java.io.InputStream. Default implementations always return a java.io.BufferedInputStream. Default implementations are defined for InputStream, File, URI, URL, Socket, byte array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the InputStream is properly closed.
(require '(clojure.java [io :as io]))
;; A common task it to load a file into a byte array.
(defn file->bytes [file]
(with-open [xin (io/input-stream file)
xout (java.io.ByteArrayOutputStream.)]
(io/copy xin xout)
(.toByteArray xout)))
;=> #'boot.user/file->bytes
(file->bytes (io/file "/foo-pc" "junk.txt"))
;=> #object["[B" 0x7813db81 "[B@7813db81"]
(require '[clojure.java.io :as io])
;; these return a java.io.BufferedInputStream for a local file:
(io/input-stream "file.txt")
(io/input-stream "/home/user/file.txt")
(io/input-stream "file:///home/user/file.txt")
(io/input-stream (java.io.File. "/home/user/file.txt"))
(io/input-stream (java.io.FileInputStream. "file.txt"))
(io/input-stream (java.net.URL. "file:///home/user/file.txt"))
(io/input-stream (java.net.URI. "file:///home/user/file.txt"))
;; these return a java.io.BufferedInputStream for a remote resource:
(io/input-stream "http://clojuredocs.org/")
(io/input-stream (java.net.URL. "http://clojuredocs.org"))
(io/input-stream (java.net.URI. "http://clojuredocs.org"))
(let [socket (java.net.Socket. "clojuredocs.org" 80)
out (java.io.PrintStream. (.getOutputStream socket))]
(.println out "GET /index.html HTTP/1.0")
(.println out "Host: clojuredocs.org\
\
")
(io/input-stream socket))
;; these return a java.io.BufferedInputStream from an in-memory source:
(io/input-stream (.getBytes "text"))
(io/input-stream (java.io.ByteArrayInputStream. (.getBytes "text")))
(io/input-stream (byte-array [116 101 120 116]))