Java nio 文件:readAllBytes 与 readAllLines?什么时候使用哪个?

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

我正在尝试了解与 Java nio 文件的这两种方法相关的最佳实践 class:

readAllLines vs readAllBytes

什么时候使用哪个?大多数结果来自 google return 一种使用它们的方式,但没有涉及何时使用它们。

有人可以帮我理解吗?

来自 readAllLines 文档(强调我自己的):

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

所以马上,你被告知 readAllLines 将通过 UTF-8 字符集自动解码字符串。这意味着至少,当您 NOT 处理 UTF-8 字符集时,您不应该使用它,而是将文件存储在 UTF-16 或 UTF-32 中(或其他一些非 UTF-8 字符集)。

此外,您并不总是处理字符串,有时您正在处理:

  • 二进制数据,可以读取并反序列化为其他对象。
  • 图像数据。

所以从我的角度来看,readAllLines 基本上是一个 readAllBytes,在它之上进行了一些额外的处理(将字节转换为字符串列表)。