-3

I write to file some text after check by XmlParser. All work fine, but code, don't close that file, then i have problem latter in program with it. It create .tmp file. How close my file after that action ?

def path = new File("my/path"))
def xml = new XmlParser().parse(path)
        xml.appendNode("include", [
                myAppendToCheck"
        ])
        XmlUtil.serialize(xml, path.newOutputStream())            

    path.newOutputStream().flush()
    path.newOutputStream().close()
tim_yates
  • 167,322
  • 27
  • 342
  • 338
John Doe
  • 147
  • 1
  • 1
  • 10

2 Answers2

2

The problem here is that you create 3 different output streams. Just store the stream in a variable:

def stream = path.newOutputStream()
XmlUtil.serialize(xml, stream)
stream.close()

Note also that flush is not necessary before the stream is closed.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

Just use withOutputStream

def path = new File("my/path"))
def xml = new XmlParser().parse(path)

xml.appendNode("include", [
    myAppendToCheck"
])

path.withOutputStream { os ->
    XmlUtil.serialize(xml, os)            
}

That will close the stream for you when the closure finishes...

i'm still newbie in java

And this is Groovy, not Java ;-)

tim_yates
  • 167,322
  • 27
  • 342
  • 338