Skip to content
Rajesh R edited this page Jun 16, 2024 · 1 revision

You can always access the Java I/O classes:

val file: File = tmp / "hello.txt"
val javaFile     : java.io.File                 = file.toJava
val uri          : java.net.URI                 = file.uri
val url          : java.net.URL                 = file.url
val reader       : java.io.BufferedReader       = file.newBufferedReader()
val outputstream : java.io.OutputStream         = file.newOutputStream()
val writer       : java.io.BufferedWriter       = file.newBufferedWriter()
val inputstream  : java.io.InputStream          = file.newInputStream()
val path         : java.nio.file.Path           = file.path
val fs           : java.nio.file.FileSystem     = file.fileSystem
val channel      : java.nio.channel.FileChannel = file.newFileChannel()
val ram          : java.io.RandomAccessFile     = file.newRandomAccess()
val fr           : java.io.FileReader           = file.newFileReader()
val fw           : java.io.FileWriter           = file.newFileWriter(append = true)
val printer      : java.io.PrintWriter          = file.newPrintWriter()

The library also adds some useful implicits to above classes e.g.:

file1.reader() > file2.writer ()      // pipes a reader to a writer
System.in > file2.out             // pipes an inputstream to an outputstream
src.pipeTo(sink)                  // if you don't like symbols

val bytes   : Iterator[Byte]        = inputstream.bytes()
val bis     : BufferedInputStream   = inputstream.buffered()
val bos     : BufferedOutputStream  = outputstream.buffered()
val reader  : InputStreamReader     = inputstream.reader()
val writer  : OutputStreamWriter    = outputstream.writer()
val printer : PrintWriter           = outputstream.printWriter()
val br      : BufferedReader        = reader.buffered()
val bw      : BufferedWriter        = writer.buffered()
val mm      : MappedByteBuffer      = fileChannel.toMappedByteBuffer()
val str     : String                = inputstream.asString()  //Read a string from an InputStream
val in      : InputStream           = str.inputStream()
val reader  : Reader                = str.reader()
val lines   : Seq[String]           = str.lines()

better-files also supports certain conversions that are not supported out of the box by the JDK

Clone this wiki locally