WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Scala - Files I/O


Scala is open to utilize any Java objects and java.io.File is one of the articles which can be utilized in Scala programming to read and write files.

import java.io._

object Demo {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("test.txt" ))

      writer.write("Hello Scala")
      writer.close()
   }
}

Save the above program in Demo.scala. The commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo
It will make a document named Demo.txt in the present index, where the program is set. Coming up next is the substance of that document.

Output

Hello Scala

Reading a Line from Command Line

At some point you have to read client input from the screen and afterward continue for some further processing. Sometime model program tells you the best way to read input from the command line.

Reading File Content

Reading from files is extremely basic. You can utilize Scala's Source class and its buddy item to read files. Following is the precedent which tells you the best way to peruse from "Demo.txt" document which we made earlier.

Command

\>scalac Demo.scala
\>scala Demo

Output

Following is the content read:
Hello Scala