Scala tipy: Jak načíst soubor jako string / čtení binárního souboru / čtení souboru z URL

Krátký příspěvek s tipy pro práci se soubory v jazyce Scala.

Doporučuji si přečíst dokumentaci k objektu Source a Scala.io._, pro přehled o dalších možnostech použití.

Načtení souboru jako řetězec (String)

$ scala
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Client VM, Java 1.6.0_20).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.io.Source
import scala.io.Source

scala> Source.fromFile("file").mkString
res0: String =
This
is a
file !

scala>

Čtení binárního souboru

[EDIT: 24.7.2010]
Původní řešení, ač vypadalo elegantně, nefungovalo pro skutečné binární soubory. Během brouzdaní Scalovskými knihovnami jsem narazil na zajímavou rekurzivní myšlenku, jak se dá (obecně) z InputStreamů číst. Konstanta ch je typu Int.

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

scala> val f = new FileInputStream("file")
f: java.io.FileInputStream = java.io.FileInputStream@127077b

scala> def read():Unit = {
     | val ch = f.read
     | if (ch != -1) {
     | print(ch.toChar)
     | read
     | }
     | }
read: ()Unit

scala> read
This
is a
file !
scala>

Čtení souboru z URL

scala> import scala.io.Source
import scala.io.Source

scala> Source.fromURL("http://lampsvn.epfl.ch/svn-repos/scala/scala/trunk/docs/examples/futures.scala").mkString
res3: String =
package examples

import concurrent.ops._

object futures {
  def someLengthyComputation = 1
  def anotherLengthyComputation = 2
  def f(x: Int) = x + x
  def g(x: Int) = x * x

  def main(args: Array[String]) {
    val x = future(someLengthyComputation)
    anotherLengthyComputation
    val y = f(x()) + g(x())
    println(y)
  }
}

scala>
  • Share/Bookmark

Zanechat odpověď