Basic Read Write

These examples are a quick introduction to performing basic IO using the Scala IO API

Basic Input

Examples of basic IO
    import scalax.io._
    import scalax.io.Resource
    import java.net.URL
    import java.io.{
      InputStreamReader
    }

    // Note that in these example streams are closed automatically
    // Also note that normally a constructed stream is not passed to factory method because most factory methods are by-name parameters (=> R)
    // this means that the objects here can be reused without worrying about the stream being previously emptied
    val url = new URL("www.scala-lang.org")

    val input:Input = Resource.fromInputStream(url.openStream())

    // The simplest way to read data is to read bytes from an Input object
    val bytes: ResourceView[Byte] = input.bytes

    // you can also get the characters and strings from an Input object but you need a codec for decoding the bytes
    val chars: ResourceView[Char] = input.chars(Codec.UTF8)

    implicit val defaultCodec: Codec = Codec.UTF8

    // by declaring an _implicit_ codec I do not need to declare the codec explicitly in the next examples
    val chars2: ResourceView[Char] = input.chars

    // TODO make Lines return a ResourceView[String]
    // one can also iterate across all lines.  The line ending can be autodetected or can be explicitly declared
    val lines_Autodetect: Traversable[String] = input.lines(Line.Terminators.Auto())
    val lines_NewLineChar: Traversable[String] = input.lines(Line.Terminators.NewLine)
    val lines_CarriageReturn: Traversable[String] = input.lines(Line.Terminators.CarriageReturn)
    val lines_BothCarriageAndNewLine: Traversable[String] = input.lines(Line.Terminators.RNPair)
    val lines_CustomLineTerminator: Traversable[String] = input.lines(Line.Terminators.Custom("|"))
    val lines_KeepTerminator = input.lines(includeTerminator = true)

    // In some cases a ReadChars object is more useful.  One advantage is that the codec is already specified so the
    // codec is not needed to read characters.  Also if you start with a Reader object only a ReadChars object can
    // be constructed
    Resource.fromInputStream(url.openStream()).reader(defaultCodec).lines() foreach println _

    // Example of constructing a ReadChars object from a Reader
    Resource.fromReader(new InputStreamReader(url.openStream())).lines() foreach println _