在 Clojure 1.3 中,如何读写文件 [英] In Clojure 1.3, How to read and write a file
问题描述
我想知道在 clojure 1.3 中读写文件的推荐"方式.
I'd like to know the "recommended" way of reading and writing a file in clojure 1.3 .
- 如何读取整个文件
- 如何逐行读取文件
- 如何写一个新文件
- 如何在现有文件中添加一行
推荐答案
假设我们在这里只处理文本文件,而不是一些疯狂的二进制文件.
Assuming we're only doing text files here and not some crazy binary stuff.
第 1 点:如何将整个文件读入内存.
(slurp "/tmp/test.txt")
当文件很大时不推荐使用.
Not recommended when it is a really big file.
数字 2:如何逐行读取文件.
(use 'clojure.java.io)
(with-open [rdr (reader "/tmp/test.txt")]
(doseq [line (line-seq rdr)]
(println line)))
with-open
宏负责在正文的末尾关闭阅读器.reader 函数将一个字符串(它也可以做一个 URL 等)强制转换为 BufferedReader
.line-seq
提供一个惰性序列.要求惰性序列的下一个元素导致读取器读取一行.
The with-open
macro takes care that the reader is closed at the end of the body. The reader function coerces a string (it can also do a URL, etc) into a BufferedReader
. line-seq
delivers a lazy seq. Demanding the next element of the lazy seq results into a line being read from the reader.
请注意,从 Clojure 1.7 开始,您还可以使用转换器来读取文本文件.
Note that from Clojure 1.7 onwards, you can also use transducers for reading text files.
第 3 点:如何写入新文件.
(use 'clojure.java.io)
(with-open [wrtr (writer "/tmp/test.txt")]
(.write wrtr "Line to be written"))
同样,with-open
注意 BufferedWriter
在正文的末尾关闭.Writer 将字符串强制转换为 BufferedWriter
,您可以通过 java interop 使用该字符串:(.write wrtr "something").
Again, with-open
takes care that the BufferedWriter
is closed at the end of the body. Writer coerces a string into a BufferedWriter
, that you use use via java interop: (.write wrtr "something").
你也可以使用spit
,与slurp
相反:
You could also use spit
, the opposite of slurp
:
(spit "/tmp/test.txt" "Line to be written")
数字 4:在现有文件中追加一行.
(use 'clojure.java.io)
(with-open [wrtr (writer "/tmp/test.txt" :append true)]
(.write wrtr "Line to be appended"))
同上,但现在有附加选项.
Same as above, but now with append option.
或者再次使用spit
,与slurp
相反:
Or again with spit
, the opposite of slurp
:
(spit "/tmp/test.txt" "Line to be written" :append true)
PS: 为了更明确地说明您正在读取和写入 File 而不是其他内容,您可以先创建一个 File 对象,然后将其强制转换为 BufferedReader
或作家:
PS: To be more explicit about the fact that you are reading and writing to a File and not something else, you could first create a File object and then coerce it into a BufferedReader
or Writer:
(reader (file "/tmp/test.txt"))
;; or
(writer (file "tmp/test.txt"))
文件函数也在clojure.java.io中.
The file function is also in clojure.java.io.
PS2: 有时能够看到当前目录(所以.")是很方便的.可以通过两种方式获取绝对路径:
PS2: Sometimes it's handy to be able to see what the current directory (so ".") is. You can get the absolute path in two ways:
(System/getProperty "user.dir")
或
(-> (java.io.File. ".") .getAbsolutePath)
这篇关于在 Clojure 1.3 中,如何读写文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!