Corresponding to stdin, stdout, and stderr, clojure provide three symbols by default: * In *, * out *, and * err.
You can use the binding macro to perform redirection. For example, the following example redirects * out * to a file:
user=> (binding [*out* (java.io.FileWriter. "/home/chenshu/tt")] (println "Write to tt.") (flush))nil
Statements originally output to the console are now written to the TT file. Note that (flush) is used to write data in the buffer to * out.
This redirection is only valid in the binding expression. After leaving this expression, * out * is still stdout.
You can directly read the file and use the slurp function ):
user=> (slurp "/home/chenshu/a.xml")"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<service>\n <mongodb>\n <uri>localhost</uri>\n </mongodb>\n <socket>\n <port_number>7777</port_number> \n <login_timeout>200</login_timeout>\n <check_timeout>200</check_timeout>\n </socket>\n</service>\n"
Write a program to read the configuration file and save the content to VaR for future use:
user=> (def s (slurp "/home/chenshu/a.xml"))#'user/suser=> s"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<service>\n <mongodb>\n <uri>localhost</uri>\n </mongodb>\n <socket>\n <port_number>7777</port_number> \n <login_timeout>200</login_timeout>\n <check_timeout>200</check_timeout>\n </socket>\n</service>\n"
The above redirection is not required. You can use the following function spit to write files:
user=> (spit "b.xml" s)niluser=> (slurp "b.xml")"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<service>\n <mongodb>\n <uri>localhost</uri>\n </mongodb>\n <socket>\n <port_number>7777</port_number> \n <login_timeout>200</login_timeout>\n <check_timeout>200</check_timeout>\n </socket>\n</service>\n"user=>
The clojure language is also evolving. You should pay attention to the official documentation.
I/O documentation is mainly in: http://clojure.org/cheatsheet Io section.
Also: http://clojure.github.com/clojure/clojure.java.io-api.html
Also here can refer to: http://java.ociweb.com/mark/clojure/article.html#IO