View Category
Read the contents of a file into a string
scala
val text = FileUtils.readFileToString(new File("Solution467.scala"))
val text = Source.fromFile("Solution1256.scala").mkString("")
Process a file one line at a time
Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
1> First line of file
2> Second line of file
3> Third line of file
scala
val source = Source.fromFile(new File("Solution468.scala")).getLines
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
val source = Source.fromFile(new File("Solution469.scala")).getLines
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }
Write a string to a file
scala
FileUtils.writeStringToFile(new File("test.txt"), "This line overwites file contents!")
val fw = new FileWriter("test.txt") ; fw.write("This line overwites file contents!") ; fw.close()
Append to a file
scala
val fw = new FileWriter("test.txt", true) ; fw.write("This line appended to file!") ; fw.close()
Process each file in a directory
scala
for (file <- new File("c:\\").listFiles) { processFile(file) }
Process each file in a directory recursively
scala
processDirectory(new File("c:\\"))
