Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala File I/O

Scala File I/O

Scala uses the I/O classes from java directly for file write operations (java.io.File):

Example

import

java.

io

.

_

object

Test

{

   

def

main

(

args

:

Array

[

String

]

)

{

     

val

writer

=

new

PrintWriter

(

new

File

(

"test.txt"

)

)

      writer.

write

(

"Runoob Tutorial"

)

      writer.

close

(

)

   

}

}

Running the above code will produce a test.txt file in your current directory, with the content "Runoob Tutorial":



$ scalac Test.scala 

$ scala Test

$ cat test.txt 

Runoob Tutorial


Reading User Input from the Screen

Sometimes we need to receive commands entered by the user on the screen to process a program. For example:

Example

import

scala.

io

.

_

object

Test

{

   

def

main

(

args

:

Array

[

String

]

)

{

      print

(

"Please enter the Runoob Tutorial website: "

)

     

val

line

=

StdIn.

readLine

(

)

      println

(

"Thank you, you entered: "

)

   

}

}

Versions after Scala 2.11 Console.readLine is deprecated; use scala.io.StdIn.readLine() method instead.

Running the above code displays the following information on the screen:



$ scalac Test.scala 

$ scala Test

请输入Runoob Tutorial官网 : www.runoob.com

谢谢,你输入的是: www.runoob.com


Reading Content from a File

Reading content from a file is very simple. We can use Scala's Source class and its companion object to read the file. The following example demonstrates reading content from the "test.txt" file (created earlier):

Example

import

scala.

io

.

Source

object

Test

{

   

def

main

(

args

:

Array

[

String

]

)

{

      println

(

"File content: "

)

      Source.

fromFile

(

"test.txt"

)

.

foreach

{

         print

     

}

   

}

}

Running the above code produces the following output:



$ scalac Test.scala 

$ scala Test

The file content is:

Runoob Tutorial