将“line-seq”与“reader”一起使用,文件何时关闭?
我正在使用 (line-seq (reader "input.txt"))
从文本文件中读取行。然后这个集合被我的程序传递和使用。
然而,我担心这可能是不好的风格,因为我没有确定性地关闭文件。我想我不能使用 (with-open (line-seq (reader "input.txt")))
,因为文件流可能会在我遍历整个序列之前关闭。
是否应该避免将“lazy-seq”与“reader”结合使用来读取文件?我应该在这里使用不同的模式吗?
I'm reading lines from a text file using (line-seq (reader "input.txt"))
. This collection is then passed around and used by my program.
I'm concerned that this may be bad style however, as I'm not deterministically closing the file. I imagine that I can't use (with-open (line-seq (reader "input.txt")))
, as the file stream will potentially get closed before I've traversed the entire sequence.
Should lazy-seq
be avoided in conjunction with reader
for files? Is there a different pattern I should be using here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于这并没有真正的明确答案(它全部混合到第一个答案的注释中),因此它的本质是:
这将强制读取整个行序列并关闭文件。然后您可以传递整个表达式的结果。
处理大文件时,您可能会遇到内存问题(将整个行序列保留在内存中),此时最好反转程序:
在这种情况下,您可能需要也可能不需要 doall,具体取决于我的程序返回和/或我的程序是否延迟使用序列。
Since this doesn't really have a clear answer (it's all mixed into comments on the first answer), here's the essence of it:
That will force the whole sequence of lines to be read and close the file. You can then pass the result of that whole expression around.
When dealing with large files, you may have memory problems (holding the whole sequence of lines in memory) and that's when it's a good idea to invert the program:
You may or may not need doall in that case, depending on what my-program returns and/or whether my-program consumes the sequence lazily or not.
看起来像 clojure .contrib.duck-streams/read-lines 正是您所寻找的。
read-lines
在没有输入时关闭文件,并像line-seq
一样返回序列。尝试查看read-lines
的源代码。It seems like the clojure.contrib.duck-streams/read-lines is just what you are looking for.
read-lines
closes the file when there is no input and returns the sequence just likeline-seq
. Try to look at source code ofread-lines
.