有人可以将此代码转换为clojure吗
BufferedReader br = new BufferedReader(new FileReader(args[0]));
// Read in first line, if nothing, inputString is null
String inputString = br.readLine(); // First line is header
inputString = br.readLine();
while (inputString != null) {
rowCount++;
}
我理解需要使用recur,但是,因为我正在读取文件并且行计数是一个不可变的值,我怎么能增加它以使值在while循环中继续增加。
答案 0 :(得分:2)
如果你需要的只是文件中的行数,你可以这样做:
(defn count-lines[file]
(with-open [r (clojure.java.io/reader file)]
(count (line-seq r))))
或者,如果你想对每一行做某事(例如,打印它):
(defn count-lines[file]
(with-open [r (clojure.java.io/reader file)]
(loop [i 1
s (line-seq r)]
(println (first s))
(if (seq (rest s))
(recur (inc i) (rest s)) i))))
答案 1 :(得分:0)
(defn read-lines [file]
(clojure.string/split-lines (slurp file)))
; count the number of lines
(count (read-lines "c:/test.log"))
; returns a list of indexed lines
(map-indexed vector (read-lines "c:/test.log"))
;[[0 "Line 1"]
; [1 "Line 2"]
; [2 "Line 3"]
; ...]