Scala performs file writing operations, directly using the I/O class in java ( Execute the above code and one will be produced in your current directory Sometimes we need to receive instructions entered by the user on the screen to process the program. Examples are as follows: Post-Scala2.11 version Execute the above code, and the following information will be displayed on the screen: Reading from a file is very simple. We can use Scala’s Execute the above code, and the output is as follows:
java.io.File
): 8.42.1. Example #
import java.io.\_
object Test {
def main(args: Array[String]) {
val writer = new PrintWriter(new File("test.txt" ))
writer.write("Novice Tutorial")
writer.close()
}
}
test.txt
file, the content of which is “Rookie course”:$ scalac Test.scala
$ scala Test
$ cat test.txt
Novice Tutorial
Read user input from the screen #
8.42.2. Example #
import scala.io.\_
object Test {
def main(args: Array[String]) {
print("Please enter the Rookie Tutorial official website : " )
val line = StdIn.readLine()
println("Thank you, what you entered is: " + line)
}
}
Console.readLine
abandoned, using
scala.io.StdIn.readLine()
method instead of.$ scalac Test.scala
$ scala Test
Please enter the Rookie Tutorial official website : www.runoob.com
Thank you, what you entered is: www.runoob.com
Read content from a file #
Source
class andaccompanying objects to read the file. The following example demonstrates reading from a “test.txt” (previously created) file: 8.42.3. Example #
import scala.io.Source
object Test {
def main(args: Array[String]) {
println("The file content is:" )
Source.fromFile("test.txt" ).foreach{
print
}
}
}
$ scalac Test.scala
$ scala Test
The file content is:
Novice Tutorial