How to read gzip'd file in Scala

我怕爱的太早我们不能终老 提交于 2021-02-04 10:37:06

问题


In Java, I'd wrap a GZIPInputStream over a FileInputStream and be done. How is the equivalent done in Scala?

Source.fromFile("a.csv.gz")....

fromFile returns a BufferedSource, which really wants to view the world as a collection of lines.

Is there no more elegant way than this?

Source.fromInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream("a.csv.gz"))))

回答1:


If you want to use Source and not do everything the Java way, then yes, you'll have to add one more layer of wrapping to what you were doing in Java. Source takes InputStreams but can give you Readers, which prevents you from using Source twice.

Scala is pretty good at making you never have to do more work than in Java, but especially with I/O, you often have to fall back to Java classes. (You can always define your own shortcuts, of course:

def gis(s: String) = new GZIPInputStream(new BufferedInputStream(new FileInputStream(s)))

is barely longer than what you've typed already, and now you can reuse it.)




回答2:


I would eliminate BufferedInputStream usage in stream construction -> new GZIPInputStream(new FileInputStream("a.csv.gz"))



来源:https://stackoverflow.com/questions/14940099/how-to-read-gzipd-file-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!