Bobby Tables
Bobby Tables

Reputation: 1184

Not writing to the file Scala

I have the following code, which is supposed to write to a file one line at a time, until it reaches ^EOF.

import java.io.PrintWriter
import java.io.File
object WF {
  def writeline(file: String)(delim: String): Unit = {
    val writer = new PrintWriter(new File(file))
    val line = Console.readLine(delim)
    if (line != "^EOF") {
      writer.write(line + "\n")
      writer.flush()
    }
    else {
      sys.exit()
    }
  }
}
var counter = 0
val filename = Console.readLine("Enter a file: ")
while (true) {
  counter += 1
  WF.writeline(filename)(counter.toString + ": ")
}

For some reason, at the console, everything looks like it works fine, but then, when I actually read the file, nothing has been written to it! What is wrong with my program?

Upvotes: 0

Views: 755

Answers (3)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297275

I'm guessing the problem is that you forgot to close the writer.

Upvotes: 0

Travis Brown
Travis Brown

Reputation: 139058

Every time you create a new PrintWriter you're wiping out the existing file. Use something like a FileWriter, which allows you to specify that you want to open the file for appending:

val writer = new PrintWriter(new FileWriter(new File(file), true))

That should work, although the logic here is pretty confusing.

Upvotes: 3

brandon
brandon

Reputation: 675

Use val writer = new FileWriter(new File(file), true) instead. The second parameter tells the FileWriter to append to the file. See http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html

Upvotes: 1

Related Questions