Holiday seven

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:

  1. Scale > import  java . I . PrintWriter 
  2. import java.io.PrintWriter
  3. scala> val out = new PrintWriter("output.txt")
  4. out: java.io.PrintWriter = java.io.PrintWriter@25641d39
  5. scala> for (<- 1 to 5) out.println(i)
  6. scala> out.close()

If we want to save the file to a specified directory, you need to give the file path, as follows:

  1. Scale > import  java . I . PrintWriter 
  2. import java.io.PrintWriter
  3. scala> val out = new PrintWriter("/usr/local/scala/mycode/output.txt")
  4. out: java.io.PrintWriter = java.io.PrintWriter@25641d39
  5. scala> for (<- 1 to 5) out.println(i)
  6. scala> out.close()

Read a text file line:

Use Scala.io.Source of getLines way to achieve reading for all lines of the file:

  1. Scale > Import  scale . I . Source 
  2. Import  scale . I . Source
  3. scala> val inputFile = Source.fromFile("output.txt")
  4. inputFile: scala.io.BufferedSource = non-empty iterator
  5. scala> val lines = inputFile.getLines
  6. lines: Iterator[String] = non-empty iterator 
  7. scala> for (line <- lines) println(line)

Guess you like

Origin www.cnblogs.com/jbwen/p/12275187.html