Home

Writing text files

Writing text files

To create and write to a text file, you create a java.io.PrintWriter object with a given file name. This object has methods print and println for writing to the file. When you are done, you should call the close() method of the PrintWriter:

import java.io.PrintWriter
val s = new PrintWriter("test.txt")
for (i <- 1 to 10) {
  s.print(i)
  s.print(" --> ")
  s.println(i * i)
}
s.close()
The PrintWriter object also has a printf method, but this doesn't work with numeric Scala types (PrintWriter is a Java class and doesn't integrate perfectly into the Scala type system). If you want to write formatted text, you should use the format method:
import java.io.PrintWriter
val s = new PrintWriter("test.txt")
for (i <- 1 to 10)
  s.print("%3d --> %d\n".format(i, i*i))
s.close()