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

不羁的心 提交于 2019-12-04 05:24:17

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