Somjit
Somjit

Reputation: 2772

Java nio Files: readAllBytes vs readAllLines ? Which to use when?

I'm trying to understand the best practices related to these two methods of the Java nio Files class:

readAllLines vs readAllBytes

Which to use when ? Most results from google return a way to use them, but doesn't touch upon when to use one over the other.

Can someone please help me understand ?

Upvotes: 2

Views: 1214

Answers (1)

npinti
npinti

Reputation: 52185

From the readAllLines documentation (emphasis my own):

Read all lines from a file. Bytes from the file are decoded into characters using the UTF-8 charset.

So right off the bat, you are told that readAllLines will automatically decode strings through the UTF-8 character set. This means that at the very least, you shouldn't use it when you are NOT dealing with the UTF-8 charset, but rather you have files stored in UTF-16 or UTF-32 (or some other, non UTF-8 character set).

Also, you don't always deal with strings, sometimes you are dealing with:

  • Binary data, which could be read and deserialized into some other object.
  • Image data.

So from my viewpoint, readAllLines is basically a readAllBytes with some extra processing on top of it (to transform bytes into a list of strings).

Upvotes: 4

Related Questions