Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
Scala /
file operations
Read a file line by lineimport scala.io.Source def main() { val fname = "island.txt" val src = Source.fromFile(fname, "utf-8") // Open file. Omit encoding if the file uses the platform's default encoding. for (line <- src.getLines) { // getLines is an iterator println(line) // line has no newline at its end } src.close // Close file. Don't forget it! } Read the lines into an Arrayval fname = "island.txt" val src = Source.fromFile(fname, "utf-8") val lines = src.getLines.toArray // read the whole content into an array src.close // close it println(lines.mkString(", ")) // visualize the content of the array println("Number of lines: %d.".format(lines.length)) Instead of an Read the file's entire content into a stringdef main() { val fname = "island.txt" val src = Source.fromFile(fname, "utf-8") val content = src.mkString // content to string src.close // close it println(content) } Read a file char by chardef main() { val fname = "island.txt" val src = Source.fromFile(fname, "utf-8") for (c <- src) { print(c) } src.close } Process a file word by worddef main() { val fname = "island.txt" val src = Source.fromFile(fname, "utf-8") for (line <- src.getLines) { for (w <- line.split("\\s+")) { // split the line by whitespaces println(w) } } src.close } Writing to a fileimport java.io.PrintWriter def main() { val out = new PrintWriter("out.txt") // notice the "new" operator for (i <- 1 to 10) { out.println(i) } out.println("__END__") out.close // close it } For writing, Scala borrows |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |