如何使用getResourceAsStream()循环多行?

时间:2016-01-04 21:50:56

标签: java scala stream resources classloader

我有以下Scala代码:

  @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")
    }
  }

当myInput.txt只有一行时,代码工作正常。但是,我想知道myInput.txt何时有多行,如何将data_in分成多行并使用MyTool.process()处理每一行?

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试像这样使用 scala.io.Source.fromInputStream

  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")
    }
  }