我可以找到很多例子,但它们似乎要么主要依赖Java库,要么只是读取字符/行等。
我只想使用Scala库读取一些文件并获得一个字节数组 - 有人可以帮我吗?
我可以找到很多例子,但它们似乎要么主要依赖Java库,要么只是读取字符/行等。
我只想使用Scala库读取一些文件并获得一个字节数组 - 有人可以帮我吗?
Java 7:
import java.nio.file.{Files, Paths}
val byteArray = Files.readAllBytes(Paths.get("/path/to/file"))
我相信这是可能的最简单的方式。只需利用现有的工具。NIO.2 很棒。
val bis = new BufferedInputStream(new FileInputStream(fileName))
val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray
val bis = new java.io.BufferedInputStream(new java.io.FileInputStream(fileName));
的意思是创建一个名为bis
的变量,该变量将打开指定文件名的输入流并进行缓冲处理。 - BeniBela库scala.io.Source存在问题,在读取二进制文件时不应使用它。
出错信息可以按照此处的说明进行复现:https://github.com/liufengyun/scala-bug
在文件data.bin
中,包含十六进制数0xea
,它的二进制表示为11101010
,应该转换为十进制数234
。
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
}
}
scala main.scala
时,程序输出如下:Scala:205
Java:234
Java库生成正确的输出,而Scala库则不是。
Source.fromFile("data.bin", "ISO8859-1")
,它能够正常工作。 - fengyun liuval is = new FileInputStream(fileName)
val cnt = is.available
val bytes = Array.ofDim[Byte](cnt)
is.read(bytes)
is.close()
IOUtils
。import org.apache.commons.compress.utils.IOUtils
val file = new File("data.bin")
IOUtils.toByteArray(new FileInputStream(file))
def readFile(path: Path)(implicit ec: ExecutionContext): Future[Array[Byte]] = {
val p = Promise[Array[Byte]]()
try {
val channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)
val buffer = ByteBuffer.allocate(channel.size().toInt);
channel.read(buffer, 0L, buffer, onComplete(channel, p))
}
catch {
case t: Exception => p.failure(t)
}
p.future
}
private def onComplete(channel: AsynchronousFileChannel, p: Promise[Array[Byte]]) = {
new CompletionHandler[Integer, ByteBuffer]() {
def completed(res: Integer, buffer: ByteBuffer): Unit = {
p.complete(Try {
buffer.array()
})
}
def failed(t: Throwable, buffer: ByteBuffer): Unit = {
p.failure(t)
}
}
}
import scala.io.StdIn.readLine
import scala.io.Source.fromFile
readFile("C:/users/xxxx/Downloads/", "39025968_ccccc_1009.csv")
def readFile(loc :String,filenm :String): Unit ={
var flnm = fromFile(s"$loc$filenm") // Imported fromFile package
println("Files testing")
/*for (line <- flnm.getLines()) {
printf("%4d %s\n", line.length, line)
}*/
flnm.getLines().foreach(println) // getLines() is imported from readLines.
flnm.close()
}