scala 一般用于网络上消息的处理,比如读写 mongodb, 处理 http request. 但偶尔写个 script, 还是要读写个文件的.

scala 包装了一个 Source 类,可以读取各种来源的数据, url, file 都可以. 但似乎并没有对写数据做什么处理.

scala 读取文件很容易

def fileReading(path:String) {
    import java.io.File
    import scala.io.Source
    val s = Source.fromFile(new File(path)).getLines()
    s.foreach(println(_))
}

而对于写文件,我们还是使用 java 的类. 一种是 PrintWriter

def fileWriting(path: String) {
    import java.io.{File, PrintWriter}
    val pw = new PrintWriter(new File(path))
    (0 to 10).foreach { x =>
        pw.append(s"data: $x").write("\n")
    }
    pw.flush
    pw.close
}

另一种是 BufferedWriter

def fileWriting(path: String) {
    import java.io.{File, BufferedWriter, FileWriter}
    val pw = new BufferedWriter(new FileWriter(new File(path)))
    (0 to 10).foreach { x =>
        pw.append(s"data: $x").write("\n")
    }
    pw.flush
    pw.close
}

两者效果应该是等价的,不过 print 个 string, 我觉得拣短的写比较爽.

Categories: Code

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

1 Comment

Leave a Reply

Your email address will not be published.