read the file(scala)
- two approaches{io.source / try-finally}
- 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.
- 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()
}
浙公网安备 33010602011771号