码迷,mamicode.com
首页 > 其他好文 > 详细

read the file(scala)

时间:2017-09-23 17:24:31      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:top   blog   long   mini   perl   sof   ram   txt   returns   

  • two approaches
  1. Use a concise, one-line syntax. This has the side effect of leaving the file open, but can be useful in short-lived programs, like shell scripts.
  2. Use a slightly longer approach that properly closes the file.
  • scala.io.Source

1 . In Scala shell scripts, where the JVM is started and stopped in a relatively short period of time, it may not matter that the file is closed, so you can use the Scala scala.io.Source.fromFile method as shown in the following examples.

import scala.io.Source
for(line<- Source.formFile("filename").getlines){...}
val lines = Source.fromFile("/Users/Al/.bash_profile").getLines.toList
val lines = Source.fromFile("/Users/Al/.bash_profile").getLines.toArray

2 . The fromFile method returns a BufferedSource, and its getLines method treats “any of \r\n\r, or \n as a line separator (longest match),” so each element in the sequence is a line from the file.

3 . The getLines method of the Source class returns a scala.collection.Iterator.

4 . An iterator has many methods for working with a collection, and for the purposes of working with a file, it works well with the forloop, as shown.

5 . get all lines from the file as one string,also this approach has the side effect of leaving the file open as long as the JVM is running,

val fileContents = Source.fromFile(filename).getLines.mkString
  • properly closing the file

get a reference to the BufferedSource when opening the file and manually close it

val bufferedSource = Source.fromFile("example.txt")
for (line <- bufferedSource.getLines) {
    println(line.toUpperCase)
}

bufferedSource.close
  • check whether the file is open in Unix  lsof "list open files"
sudo lsof -u usrname | grep filename
  • automatically closing the resource  Loan Pattern

ensures that a resource is deterministically disposed of once it goes out of scope.

def using[A](r : Resource)(f : Resource => A) : A =
    try {
        f(r)
    } finally {
        r.dispose()
    }

 

read the file(scala)

标签:top   blog   long   mini   perl   sof   ram   txt   returns   

原文地址:http://www.cnblogs.com/yumanman/p/7581410.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!