makotan _at_ gmail dot com

少し寒くても晴れてる方が良いよね。でもScalaも良いね

いい加減ファイル書き込みは飽きたので、読み込みを作ってみた
なんか無駄なことしたくなったので・・・
無駄にStream使ってその場で読み込ませてみたり、使えば良いのに意味もなくクラス使わなかったり・・・
作りたいイメージはあるのにコンパイラが言うこと聞いてくれないパターンがあるので言語を使う上ではもうちょっとかな
でも、わりとイメージしてるものになってるので良い傾向だと思う今日この頃

  test("vfs read test 01") {
    val (toStream,close) = textFileReaderOpen(testFileName)
    val stream = toStream()
    stream.take(5).foreach(println)
    close()
  }

  def textFileReaderOpen(testFileName:String) : (()=>Stream[String],()=>Unit) = {

    def toEither[U,R](arg: Either[Throwable, U] )( p : (U) => R) : Either[Throwable, R] = {
      eith(arg)(catching(classOf[IOException]) either p(_))
    }

    def eith[U,R](arg: Either[Throwable, U] )( f : (U) => R) : R = {
      arg match {
        case Left(e) => throw e
        case Right(o) => f(o)
      }
    }
    val file = catching(classOf[IOException]) either fsManager.resolveFile(testFileName)
    val content = toEither(file)(_.getContent())
    val is = toEither(content)(_.getInputStream())
    val isr = toEither(is)(new InputStreamReader(_))
    val br = toEither(isr)(new BufferedReader(_))

    def readLine() : String = {
      eith(br)({ br => {
        val l = br.readLine()
        l
      }})
    }

    def toStream() : Stream[String] = {
      def toStr(current:Option[String]) : Stream[String] = {
        current match {
          case None => Stream.Empty
          case Some(s) => Stream.cons(s,toStr(Some(readLine())))
        }
      }
      toStr(Some(readLine()))
    }

    def close() : Unit ={
      def close(clo: Either[Throwable, { def close(): Unit }]): Unit = {
        eith(clo)(_.close)
      }
      close(br)
      close(isr)
      close(is)
      close(content)
      close(file)

    }
    (toStream,close)
  }