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

喜夏-厌秋 提交于 2019-12-06 02:19:07

问题


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.


回答1:


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




回答2:


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)




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!