Simulate input from stdin when running a scala program in intellij

前端 未结 2 824
青春惊慌失措
青春惊慌失措 2020-12-09 15:07

Is there any way to configure the command line args to intellij for stdin redirection?

Something along the lines of:

Run | Edit Run Configurations | Script P

2条回答
  •  一整个雨季
    2020-12-09 15:22

    Here is a template for a solution that has options for:

    • stdin
    • file
    • "heredoc" within the program (most likely useful for testing)

    .

      val input = """ Some string for testing ... """
    
      def main(args: Array[String]) {
        val is = if (args.length >= 1) {
          if (args(0) == "testdata") {
            new StringInputStream(input)
          } else {
            new FileInputStream(args(0))
          }
        } else {
          System.in
        }
        import scala.io._
        Source.fromInputStream(is).getLines.foreach { line =>
    

    This snippet requires use of a StringInputStream - and here it is:

      class StringInputStream(str : String) extends InputStream {
        var ptr = 0
        var len = str.length
        override def read(): Int = {
            if (ptr < len) {
              ptr+=1
              str.charAt(ptr-1)
            } else {
             -1
            }
        }
      }
    

提交回复
热议问题