Is it possible, and if yes how is it done? The usual >
and >>
that work on the Windows or Linux command line don't work in this context.
You can do it programmaticaly from console:
import java.io.FileOutputStream
import scala.Console
Console.setOut(new FileOutputStream("<output file path>"))
from now on all print
and println
would be directed into this file
It's unclear from your question exactly how you want to use such a thing. An example of what you are trying to do might help.
Here's an implicit function that will add a simple operator that writes any object as a String to a file. (Note that I'm using >>
to mean unix-style >
since >
already has meaning in Scala ("less than"). You can replace this with some other operator if you like.)
implicit def anyToFileOutput(self: Any) = new {
import java.io._
def >>(filename: String) {
val f = new BufferedWriter(new FileWriter(filename))
try {
f.write(self.toString)
} finally {
if (f != null)
f.close()
}
}
}
You would use it like this:
scala> List(1,2,3) >> "out.txt"
Which produces a file, "out.txt" in the working directory containing List(1, 2, 3)
Looks to be working fine to me:
dcs@ayanami:~/github/scala (master)$ scala -e "println(2 * 2)" > output
dcs@ayanami:~/github/scala (master)$ cat output
4
来源:https://stackoverflow.com/questions/9494014/scala-interactive-interpreter-repl-how-to-redirect-the-output-to-a-text-file