如何使用clojure.edn / read获取文件中的对象序列? [英] How to use clojure.edn/read to get a sequence of objects in a file?

查看:380
本文介绍了如何使用clojure.edn / read获取文件中的对象序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clojure 1.5引入了 clojure.edn ,其中包含一个读取函数,需要 PushbackReader



如果我想读取前五个对象,我可以这样做:

  with-open [infile(java.io.PushbackReader。(clojure.java.io/readerfoo.txt))] 
(binding [* in * infile]
(let [edn-seq (重复clojure.edn / read)]
(dorun(take 5(map println edn-seq))))))

我如何打印出所有的对象?考虑到其中一些可能是nil,它似乎需要检查EOF,或类似的东西。我想要一个类似于 line-seq 的对象序列。

解决方案

使用:eof键



http://clojure.github.com/clojure/clojure.edn-api.html


opts是映射可以包括以下键::eof - value到
在文件结束时返回。当不提供时,eof会抛出异常。


编辑:对不起,这不够详细!这里y'go:

 (with-open [java.io.PushbackReader。(clojure.java.io/reader foo.txt))] 
(let [edn-seq(repeated(partial edn / read {:eof:theend} in))]
(dorun not =:theend)edn-seq)))))


Clojure 1.5 introduced clojure.edn, which includes a read function that requires a PushbackReader.

If I want to read the first five objects, I can do:

(with-open [infile (java.io.PushbackReader. (clojure.java.io/reader "foo.txt"))]
  (binding [*in* infile]
    (let [edn-seq (repeatedly clojure.edn/read)]
      (dorun (take 5 (map println edn-seq))))))

How can I instead print out all of the objects? Considering that some of them may be nils, it seems like I need to check for the EOF, or something similar. I want to have a sequence of objects similar to what I would get from line-seq.

解决方案

Use :eof key

http://clojure.github.com/clojure/clojure.edn-api.html

opts is a map that can include the following keys: :eof - value to return on end-of-file. When not supplied, eof throws an exception.

edit: sorry, that wasn't enough detail! here y'go:

(with-open [in (java.io.PushbackReader. (clojure.java.io/reader "foo.txt"))]
  (let [edn-seq (repeatedly (partial edn/read {:eof :theend} in))]
    (dorun (map println (take-while (partial not= :theend) edn-seq)))))

that should do it

这篇关于如何使用clojure.edn / read获取文件中的对象序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆