简体   繁体   中英

Clojure: How does (reader “/tmp/test.txt”) result in a BufferedReader

I was trying to understand the following snippet of code.

use 'clojure.java.io)
(with-open [rdr (reader "/tmp/test.txt")]
  (doseq [line (line-seq rdr)]
    (println line)))

Though I can follow it at a reasonably level of fidelity I have trouble figuring out how (reader "/tmp/test.txt") result in a BufferedReader

When I search on reader and clojure I get this

In the same vane, is there a good treatment of Clojure IO -- the Java trails I read on Java IO were an excellent treatment of the subject. However I have had trouble finding a similarly succinct treatment of IO on Clojure. Unfortunately on Clojure one challenge has been that I find stuff in a very fragmented manner.

EDIT: As one of the posters has pointed out that the two readers are different -- I was aware of that -- the point I was trying to make was that I had a hard time finding the correct documentation for reader.

You mention two different kinds of readers in your post. The reader method is part of the java.io namespace, and you can check the clojure.java.io/reader API documentation to see what it does:

Usage: (reader x & opts) Attempts to coerce its argument into an open java.io.Reader. Default implementations always return a java.io.BufferedReader.

Default implementations are provided for Reader, BufferedReader, InputStream, File, URI, URL, Socket, byte arrays, character arrays, and String.

If 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 Reader is properly closed.

The reader turned up by your Google search is Clojure's implementation of the Lisp reader . The Lisp reader is what parses Clojure syntax and lets you do dynamic things like read and eval at runtime.


As for the second half of your question, I don't think there's a definitive source on I/O in Clojure. Since Clojure runs on the JVM and has full Java interop, I think your best bet is just reading through the Java Trails tutorial, then looking at the clojure.java.io API . For anything that's not nicely wrapped in the API you can either write your own wrappers, or just access the Java classes directly using Clojure syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM