English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Scala führt Datei-Schreiboperationen direkt durch, die in Java der I/Klasse (java.io.File):
import java.io._ object Test { def main(args: Array[String]) { val writer = new PrintWriter(new File("test.txt")) writer.write("Grundlagen-Tutorial-Website") writer.close() } }
After executing the above code, a test.txt file will be created in your current directory with the content "Basic Tutorial Website":
$ scalac Test.scala $ scala Test $ cat test.txt Basic Tutorial Website
Sometimes we need to receive user instructions entered on the screen to process the program. Here is an example:
import scala.io._ object Test { def main(args: Array[String]) { print("Please enter the official website of Basic Tutorial Website: ") val line = StdIn.readLine() println("Thank you, you entered: ") + line) } }
Scala2.11 in later versions Console.readLine Deprecated, use the scala.io.StdIn.readLine() method instead.
After executing the above code, the following information will be displayed on the screen:
$ scalac Test.scala $ scala Test Please enter the official website of Basic Tutorial Website: de.oldtoolbag.com Thank you, you entered: de.oldtoolbag.com
Reading content from a file is very simple. We can use Scala's Source Classes and companion objects to read files. The following example demonstrates reading content from the "test.txt" file (previously created):
import scala.io.Source object Test { def main(args: Array[String]) { println("File Content:") Source.fromFile("test.txt").foreach{ print } } }
After executing the above code, the output will be:
$ scalac Test.scala $ scala Test File Content: Basic Tutorial Website