3

I have Groovy code like this...

class GuiWindow extends SwingBuilder {

....
FileWriter writer

    GuiWindow(def controller)
{
    ....
    writer = new FileWriter("DATA${new Date().time.toString()}.txt")
    writer.write("Count, Rate\n")

This code successfully creates the file but seemingly refuses to write anything into it - not even the header line of text in the immediate next statement.

I have used very similar code before without any problem so am at a bit of a loss as to know what is wrong.

I don't close() the writer - it is meant to be open to record data which comes in slowly - so the one thing I can think of is that the writing is batched and only written when a buffer overflows - but can someone tell me what is wrong with my code or why it doesn't behave the way I expect it to?

adrianmcmenamin
  • 1,081
  • 1
  • 15
  • 44
  • 2
    I assume you've tried adding `writer.flush()` after your write to show that you're probably right about the buffering – tim_yates Dec 01 '13 at 20:28
  • 2
    Don't you like Groovy operator `<<` ;) Try that: `def out= new File('text_from_groovy.txt'); out.createNewFile(); out << 'your text';` – olyv Dec 01 '13 at 20:42
  • @olyv that will open a writer append and close it each time, which can get expensive if you do it a lot – tim_yates Dec 01 '13 at 20:52

1 Answers1

3

Just like tim_yates mentiones above, flush solved the problem in my case.

FileWriter writer = new FileWriter("DATA${new Date().time.toString()}.txt")
writer.write("Count, Rate\n")
writer.flush()
user955732
  • 1,330
  • 3
  • 21
  • 48