For reading files in Scala, there is
Source.fromFile(\"file.txt\").mkString
Is there an equivalent and concise way to write a string to fi
A micro library I wrote: https://github.com/pathikrit/better-files
file.write("Hi!")
or
file << "Hi!"
I know it's not one line, but it solves the safety issues as far as I can tell;
// This possibly creates a FileWriter, but maybe not
val writer = Try(new FileWriter(new File("filename")))
// If it did, we use it to write the data and return it again
// If it didn't we skip the map and print the exception and return the original, just in-case it was actually .write() that failed
// Then we close the file
writer.map(w => {w.write("data"); w}).recoverWith{case e => {e.printStackTrace(); writer}}.map(_.close)
If you didn't care about the exception handling then you can write
writer.map(w => {w.writer("data"); w}).recoverWith{case _ => writer}.map(_.close)
Through the magic of the semicolon, you can make anything you like a one-liner.
import java.io.PrintWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption
val outfile = java.io.File.createTempFile("", "").getPath
val outstream = new PrintWriter(Files.newBufferedWriter(Paths.get(outfile)
, StandardCharsets.UTF_8
, StandardOpenOption.WRITE)); outstream.println("content"); outstream.flush(); outstream.close()
Use ammonite ops library. The syntax is very minimal, but the breadth of the library is almost as wide as what one would expect from attempting such a task in a shell scripting language like bash.
On the page I linked to, it shows numerous operations one can do with the library, but to answer this question, this is an example of writing to a file
import ammonite.ops._
write(pwd/'"file.txt", "file contents")
It is strange that no one had suggested NIO.2 operations (available since Java 7):
import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets
Files.write(Paths.get("file.txt"), "file contents".getBytes(StandardCharsets.UTF_8))
I think this is by far the simplest and easiest and most idiomatic way, and it does not need any dependencies sans Java itself.
You can easily use Apache File Utils. Look at function writeStringToFile
. We use this library in our projects.