Search code examples
javascalastreamresourcesclassloader

How to loop over multiple lines using getResourceAsStream()?


I have the following Scala code:

  @Test def test2() = {
    try {
      val data_in = IOUtils.toString(getClass().getClassLoader()
        .getResourceAsStream("com/myProject/myPackage/myInput.txt"))

      val data_out = MyTool.process(data_in)

      println(data_out)

    } catch {
      case e: Exception =>

        println("process failed")
    }
  }

The code works fine when myInput.txt has only one line. However, I am wondering when myInput.txt has multiple lines, how do I break data_in to multiple lines and process each line using MyTool.process() ?

Thanks!


Solution

  • Try using scala.io.Source.fromInputStream like this

      import scala.io.Source
    
      @Test def test2() = {
        try {
          val data_in = getClass().getClassLoader()
            .getResourceAsStream("com/myProject/myPackage/myInput.txt")
    
          for (line <- Source.fromInputStream(data_in).getLines()) {
              val data_out = MyTool.process(line)
    
              println(data_out)
          }
    
        } catch {
          case e: Exception =>
    
            println("process failed")
        }
      }