标签:top blog long mini perl sof ram txt returns
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 for
loop, 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
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
sudo lsof -u usrname | grep ‘filename‘
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() }
标签:top blog long mini perl sof ram txt returns
原文地址:http://www.cnblogs.com/yumanman/p/7581410.html