Scala interactive interpreter (REPL) - how to redirect output to a text file?

Is it possible, and if so, how is this done? Normal > and >> that work on the Windows or Linux command line do not work in this context.

+6
source share
3 answers

You can do this programmatically from the console:

 import java.io.FileOutputStream import scala.Console Console.setOut(new FileOutputStream("<output file path>")) 

from now on, all print and println will be directed to this file

+11
source

It is not clear from your question exactly how you want to use such a thing. An example of what you are trying to do may help.

Here's an implicit function that will add a simple statement that writes any object as a string to a file. (Note that I use >> to indicate a unix style > , since > already has a value in Scala ("less"). You can replace it with some other statement if you want.)

 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 as follows:

 scala> List(1,2,3) >> "out.txt" 

What creates the file "out.txt" in the working directory containing List(1, 2, 3)

+4
source

Everything seems to work fine for me:

 dcs@ayanami :~/github/scala (master)$ scala -e "println(2 * 2)" > output dcs@ayanami :~/github/scala (master)$ cat output 4 
0
source

Source: https://habr.com/ru/post/909601/


All Articles