Scala native File I/O (Read Write)?

I’m writing this as someone with some programming knowledge and I feel this is the one area where I feel a bit lost with Scala. How does one Read and Write to/from files in Scala using Scala core/standard Libraries? Going forward to Scala 3, will this change?

Using Scala 2.13 and Java 8.

Mostly learning Scala by reading a few books and playing with the repl. I have some ideas to code more seriously now, and it struck me that I still don’t know how to read and write to a file in my favorite language.

Several online articles suggest using Java.io. I’d like to stick to Scala standard/core libraries. It doesn’t seem clear to me in Scala Docs what to use. Other results point to using Scala methods which the compiler is warning are deprecated. Instead of bringing in one of several outside libraries, is there a current way (Scala 2.13) of reading files / writing files using Scala core libraries?

1 Like

For simple things, Source is good enough. I have no idea if that’s changing in Scala 3. When it’s not enough I use classes in java.nio, which won’t.

2 Likes

Broadly speaking (and as I understand it), Scala 3 is trying not to change the standard library any more than is necessary, so I expect this will likely just keep working…

2 Likes

Thanks for replies. I’ll look into the Source libs and Java.nio.

Note that scala.io.Source is just for reading, not writing.

There’s nothing in Scala stdlib for writing, so people either use Java stdlib calls, or add a dependency on better-files or Ammonite-Ops

1 Like