09.10.2014 Views

Download Scala Tutorial (PDF Version) - Tutorials Point

Download Scala Tutorial (PDF Version) - Tutorials Point

Download Scala Tutorial (PDF Version) - Tutorials Point

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER<br />

21<br />

<strong>Scala</strong> Files I/O<br />

<strong>Scala</strong> is open to make use of any Java objects and java.io.File is one of the objects which can be used in<br />

<strong>Scala</strong> programming to read and write files. Following is an example of writing to a file:<br />

import java.io._<br />

object Test {<br />

def main(args: Array[String]) {<br />

val writer = new PrintWriter(new File("test.txt" ))<br />

}<br />

}<br />

writer.write("Hello <strong>Scala</strong>")<br />

writer.close()<br />

When the above code is compiled and executed, it creates a file with "Hello <strong>Scala</strong>" content which you can check<br />

yourself.<br />

C:/>scalac Test.scala<br />

C:/>scala Test<br />

C:/><br />

Reading line from Screen:<br />

Sometime you need to read user input from the screen and then proceed for some further processing. Following<br />

example shows you how to read input from the screen:<br />

object Test {<br />

def main(args: Array[String]) {<br />

print("Please enter your input : " )<br />

val line = Console.readLine<br />

}<br />

}<br />

println("Thanks, you just typed: " + line)<br />

When the above code is compiled and executed, it prompts you to enter your input and it continues until you press<br />

ENTER key.<br />

C:/>scalac Test.scala<br />

TUTORIALS POINT<br />

Simply Easy Learning

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!