François Beausoleil
François Beausoleil

Reputation: 16515

How to read gzip'd file in Scala

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"))))

Upvotes: 30

Views: 16175

Answers (2)

kairius
kairius

Reputation: 540

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

Upvotes: 8

Rex Kerr
Rex Kerr

Reputation: 167871

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.)

Upvotes: 24

Related Questions