File I/O in Scala: Writing Files, Reading Console Input, and Reading Files
This tutorial demonstrates how to perform file writing, read user input from the console, and read file contents in Scala by leveraging Java I/O classes, scala.io.StdIn, and scala.io.Source, complete with compile‑run commands and expected output.
Scala file write operations typically use Java I/O classes such as java.io.File . The following example creates a PrintWriter for a new File("test.txt") and writes the string "菜鸟教程" to it.
import java.io._
object Test {
def main(args: Array[String]) {
val writer = new PrintWriter(new File("test.txt"))
writer.write("菜鸟教程")
writer.close()
}
}Compiling and running the code with scalac Test.scala and scala Test generates a test.txt file in the current directory containing the text "菜鸟教程".
To receive user input from the console, Scala 2.11 and later deprecate Console.readLine in favor of scala.io.StdIn.readLine(). The example below prompts the user, reads a line, and prints a confirmation.
import scala.io._
object Test {
def main(args: Array[String]) {
print("请输入菜鸟教程官网 : ")
val line = StdIn.readLine()
println("谢谢,你输入的是: " + line)
}
}Running this program displays the prompt, accepts input such as www.runoob.com, and echoes it back.
Reading file contents is straightforward with Scala's Source class. The example reads the previously created test.txt and prints each character.
import scala.io.Source
object Test {
def main(args: Array[String]) {
println("文件内容为:")
Source.fromFile("test.txt").foreach {
print
}
}
}Executing the code prints "文件内容为:" followed by the file's content, confirming that the file was read correctly.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
