Scala is required to achieve java.io.PrintWriter write data to a text file.
When using the relative path, when a user login name hadoop Linux, open into the command interpreter Scala prompt, enter the following code:
- Scale > import java . I . PrintWriter
- import java.io.PrintWriter
- scala> val out = new PrintWriter("output.txt")
- out: java.io.PrintWriter = java.io.PrintWriter@25641d39
- scala> for (i <- 1 to 5) out.println(i)
- scala> out.close()
If we want to save the file to a specified directory, you need to give the file path, as follows:
- Scale > import java . I . PrintWriter
- import java.io.PrintWriter
- scala> val out = new PrintWriter("/usr/local/scala/mycode/output.txt")
- out: java.io.PrintWriter = java.io.PrintWriter@25641d39
- scala> for (i <- 1 to 5) out.println(i)
- scala> out.close()
Read a text file line:
Use Scala.io.Source of getLines way to achieve reading for all lines of the file:
- Scale > Import scale . I . Source
- Import scale . I . Source
- scala> val inputFile = Source.fromFile("output.txt")
- inputFile: scala.io.BufferedSource = non-empty iterator
- scala> val lines = inputFile.getLines
- lines: Iterator[String] = non-empty iterator
- scala> for (line <- lines) println(line)