simple version of java's 'try-with-resource'
simple version of java's 'try-with-resource'
exceptions aren't intercepted, only the resource will always be closed.
import sclib.io.autoClose import java.nio.file.Paths import java.nio.file.StandardOpenOption.{CREATE, WRITE} import java.nio.channels.FileChannel for { in <- autoClose(FileChannel.open(Paths.get("/tmp/input"))) out <- autoClose(FileChannel.open(Paths.get("/tmp/output"), CREATE, WRITE)) } in.transferTo(0, Long.MaxValue, out) // `in` and `out` are closed here
working with files and directories
working with files and directories
to get a file handle, use any of the following functions:
for a directory handle:
scala> import sclib.io.fs._ scala> file("/path/file-name") res0: scala.util.Try[FSFile] = Success(FSFile(/path/file-name)) scala> dir("/path/dir-name") res1: scala.util.Try[FSDir] = Success(FSDir(/path/dir-name))
this functions returns a Failure
if the requested entry exists, but has a wrong type.
scala> import sclib.io.fs._ scala> file("a-file").flatMap(_.create) res0: scala.util.Try[FSFile] = Success(FSFile(a-file)) scala> dir("a-file") res1: scala.util.Try[FSDir] = Failure(java.lang.Exception: 'a-file' is a file) scala> file("a-file").flatMap(_.delete) res2: scala.util.Try[Unit] = Success(())
all functions which can throw a exception are wrapped in a Try
, so it's easy to compose.
scala> import sclib.io.fs._ scala> for { | fh <- file("file-name") | _ <- fh.write("file content") | c <- fh.slurp | _ <- fh.delete | } yield c res0: scala.util.Try[String] = Success(file content)
fetch a file from a given url
fetch a file from a given url
to get a java.net.URL
handle, use: url(s: String): Try[URL]
scala: import sclib.io.net._ scala: url("http://example.com") scala.util.Try[java.net.URL] = Success(http://example.com) scala: url("example.com") scala.util.Try[java.net.URL] = Failure(java.net.MalformedURLException: no protocol: example.com)
scala: import sclib.io.net._ scala: import sclib.io.fs._ scala: for { | url <- url("http://example.com") // save way to get a 'java.net.URL' | local <- url.fetch(file("example.com")) // download the url-content | content <- local.slurp // read the local copy | _ <- local.delete() // delete the local copy | } yield content.take(20) res0: scala.util.Try[String] = Success(<!doctype html> <htm)