newOutputStream 关​​闭文件

newOutputStream Close file

我在 XmlParser 检查后写入了一些文本文件。 一切正常,但代码,不要关闭该文件,然后我在使用它的程序中遇到问题。它创建 .tmp 文件。该操作后如何关闭我的文件?

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()

这里的问题是您创建了 3 个不同的输出流。只需将流存储在变量中:

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

另请注意,在关闭流之前不需要刷新。

只需使用withOutputStream

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

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

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

关闭完成后将为您关闭流...

i'm still newbie in java

这是 Groovy,不是 Java ;-)