Clojureã®coreã©ã¤ãã©ãªã®ä¸ã§ããæ¥å¸¸ã§æ¯è¼ç使ããããªIOç³»ã®é¢æ°ãã¡ãã£ã¨èª¿ã¹ã¦ã¿ã¾ããã
read-line
æ¨æºå ¥åãã1è¡èªã¿è¾¼ã¿ã¾ãã以ä¸ããµã³ãã«ã
(print "type keyword => ") (flush) (def line (read-line)) (print (str "Your typed => " line)) (newline)
flushã¯æ¨æºåºåããã©ãã·ã¥ããé¢æ°ãnewlineã¯æ¨æºåºåã«æ¹è¡ãåºåããé¢æ°ã§ãããããå®è¡ããã¨ã以ä¸ã®ãããªå®è¡çµæã¨ãªãã¾ãã
type keyword => ããã«ã¡ã¯ãä¸ç Your typed => ããã«ã¡ã¯ãä¸ç
type keyword =>ã®å¾ã«ç¶ãã¦ãããããã«ã¡ã¯ãä¸çãã¯ããã¡ããèªåã§å
¥åãããã®ã§ãã
ãªããå¤æ°lineã«ãã®æå
¥åãããæååãæç¸ãã¦ãã¾ãã
spit
ãã¡ã¤ã«ãã¹ã¨æååãä¸ããã¨ããã®å
容ããã¡ã¤ã«ã«æ¸ãåºãé¢æ°ã§ãã
slurpé¢æ°ã®å¯¾ãããã§ãã以ä¸ã®ä¾ã§ã¯ãå
ã®ä¾ã§æ¨æºå
¥åããèªã¿åºããæååããæ¹è¡ä»ãã§ãã¡ã¤ã«output.txtã«åºåãã¾ãã
(spit "output.txt" (str line "\n"))
ãªãã·ã§ã³ã¨ãã¦ãclojure.java.io/writerã¨åããã®ã渡ãããã ãããªãã¤ã¾ãã以ä¸ã®ãããªæå®ãå¯è½ãããã§ãã
(spit "output.txt" (str line "\n") :append true :encoding "UTF-8")
ãã¼ã¯ã¼ãappendã§ãã¡ã¤ã«ã«è¿½è¨ãããã©ããããencodingãã¼ã¯ã¼ãã§åºåæã®æåã¨ã³ã³ã¼ãã£ã³ã°ãæå®ãã¾ãã
slurp
ä¸ãããããã¡ã¤ã«ãã¹ããããã¡ã¤ã«ã®å 容ãæååã¨ãã¦èªã¿åºãé¢æ°ã§ãã以ä¸ã®ä¾ã§ã¯ããã¡ã¤ã«output.txtãããã¡ã¤ã«ã®å 容ãèªã¿åºããæ¨æºåºåã«æ¸ãåºãã¾ãã
(print (slurp "output.txt"))
ãã¡ããããªãã·ã§ã³ã¨ãã¦clojure.java.io/readerã¨åããã®ã渡ããããã§ãã
(print (slurp "output.txt" :encoding "UTF-8"))
ãªããslurpã«ã¯URLãªã©ãå¼æ°ã¨ãã¦æ¸¡ãã¾ããä¾ãã°ã以ä¸ã®ã³ã¼ãã§Googleã®ãµã¤ãã®HTMLãã³ã³ã½ã¼ã«ã«åºåããã¾ãã
(print (slurp "http://google.co.jp"))
spitãããã§ãããä½ãå¼æ°ã¨ãã¦åããã®ãã¯clojure.java.ioå ã«å®ç¾©ããã¦ããé¢æ°ãèªãã æ¹ãããã¿ããã§ããã
with-open
ReaderãWriterãå¼æ°ã¨ãã¦æ¸¡ããå¦çã®çµäºæã«ã¯èªåçã«closeãå¼ã³åºããã¯ãã§ãã以ä¸ã使ç¨ä¾ã§ãã
(import '(java.io BufferedReader InputStreamReader FileInputStream)) (with-open [r (BufferedReader. (InputStreamReader. (FileInputStream. "output.txt")))] (loop [l (.readLine r)] (if (not= nil l) (do (println l) (recur (.readLine r))))))
ãã¡ã¤ã«ãéãã¦ãã³ã³ãã³ããããéãBufferedReader#readLineãå¼ã³åºããã³ã³ã½ã¼ã«ã«åºåãã¾ããdoããªãã¨ã1ååºåããã ãã§çµäºãã¦ãã¾ãã®ã§æ³¨æã§ãã
ä¸å¿ãä»åä½æããã³ã¼ãã®å
¨ä½ã§ãã
clj_io.clj
(print "type keyword => ") (flush) (def line (read-line)) (print (str "Your typed => " line)) (newline) ;;(spit "output.txt" (str line "\n") :append true :encoding "UTF-8") (spit "output.txt" (str line "\n")) ;;(print (slurp "output.txt" :encoding "UTF-8")) (print (slurp "output.txt")) (import '(java.io BufferedReader InputStreamReader FileInputStream)) (with-open [r (BufferedReader. (InputStreamReader. (FileInputStream. "output.txt")))] (loop [l (.readLine r)] (if (not= nil l) (do (println l) (recur (.readLine r))))))
å®è¡ä¾ã
$ clj clj_io.clj type keyword => ããã«ã¡ã¯ãä¸ç Your typed => ããã«ã¡ã¯ãä¸ç ããã«ã¡ã¯ãä¸ç ããã«ã¡ã¯ãä¸ç $ cat output.txt ããã«ã¡ã¯ãä¸ç
ä»å¾ã¯ãclojure.java.ioãè¦ã¦ãããã¨æãã¾ããããã«ãã¦ããAPIããã¥ã¡ã³ãã¯Clojureèªèº«ã®ãµã¤ããããã以ä¸ã®æ¹ãè¦ãããæ´çããã¦ãã¦ããã§ããã
http://clojuredocs.org/