scala 如何在Scala中将文件作为字节数组读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7598135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:30:46  来源:igfitidea点击:

How to read a file as a byte array in Scala

scalaiobytearray

提问by fgysin reinstate Monica

I can find tons of examples but they seem to either rely mostly on Java libraries or just read characters/lines/etc.

我可以找到大量示例,但它们似乎要么主要依赖于 Java 库,要么只是读取字符/行/等。

I just want to read in some file and get a byte array with scala libraries - can someone help me with that?

我只想读入一些文件并获得一个带有 Scala 库的字节数组 - 有人可以帮我吗?

回答by Vladimir Matveev

Java 7:

爪哇7:

import java.nio.file.{Files, Paths}

val byteArray = Files.readAllBytes(Paths.get("/path/to/file"))

I believe this is the simplest way possible. Just leveraging existing tools here. NIO.2 is wonderful.

我相信这是最简单的方法。只是利用这里的现有工具。NIO.2很棒。

回答by Jus12

This should work (Scala 2.8):

这应该有效(Scala 2.8):

val bis = new BufferedInputStream(new FileInputStream(fileName))
val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray

回答by reivzy

val is = new FileInputStream(fileName)
val cnt = is.available
val bytes = Array.ofDim[Byte](cnt)
is.read(bytes)
is.close()

回答by OlivierBlanvillain

You might also consider using scalax.io:

您也可以考虑使用scalax.io

scalax.io.Resource.fromFile(fileName).byteArray

回答by fengyun liu

The library scala.io.Sourceis problematic, DON'T USE IT in reading binary files.

scala.io.Source有问题,请勿在读取二进制文件时使用它。

The error can be reproduced as instructed here: https://github.com/liufengyun/scala-bug

错误可以按照这里的说明重现:https: //github.com/liufengyun/scala-bug

In the file data.bin, it contains the hexidecimal 0xea, which is 11101010in binary and should be converted to 234in decimal.

在文件中data.bin,它包含十六进制0xea,它是11101010二进制的,应该转换为234十进制。

The main.scalafile contain two ways to read the file:

main.scala文件包含两种读取文件的方式:

import scala.io._
import java.io._

object Main {
  def main(args: Array[String]) {
    val ss = Source.fromFile("data.bin")
    println("Scala:" + ss.next.toInt)
    ss.close

    val bis = new BufferedInputStream(new FileInputStream("data.bin"))
    println("Java:" + bis.read)
    bis.close
  }
}

When I run scala main.scala, the program outputs follows:

当我运行时scala main.scala,程序输出如下:

Scala:205
Java:234

The Java library generates correct output, while the Scala library not.

Java 库生成正确的输出,而 Scala 库则没有。

回答by Sagi

You can use the Apache Commons CompressIOUtils

您可以使用Apache Commons CompressIOUtils

import org.apache.commons.compress.utils.IOUtils

val file = new File("data.bin")
IOUtils.toByteArray(new FileInputStream(file))