Resources

Examples of using the Resource API to wrap existing Java IO objects

Using Io Resources

The typical IO objects are java IO objects converted into Resource objects using the Resource object's factory methods. Once a Resource has been created there are methods for converting between them.

The following examples demonstrate using the Resource objects and converting between them.

All resources are also Seekable, Input, Output, ReadChars and/or WriteChars so all normal IO operations are possible but the following examples are Resource only operations

    import scalax.io._
    import java.io._
    import java.nio.channels._

    val resource = Resource.fromInputStream(new FileInputStream("file"))

    // The Resource objects have methods for converting between the common types
    val bufferedInput: InputStreamResource[BufferedInputStream] = resource.buffered
    val readChars: ReaderResource[Reader] = resource.reader(Codec.UTF8)
    val readableByteChannel: ReadableByteChannelResource[ReadableByteChannel] =
              resource.readableByteChannel
    val bufferedReader = readChars.buffered

    // there are also several ways to obtain the underlying java object
    // for certain operations.  Typically this is to micro manage how the
    // data is read from the input
    val availableBytes: Int = bufferedInput.acquireAndGet{
      bufferedInputStream => bufferedInputStream.available
    }

    // If you want to perform an operation and have the option to easily
    // get the exception acquireFor is a good solution
    val firstLine: Either[scala.List[scala.Throwable], String] = bufferedReader.acquireFor{
      reader => reader.readLine
    }