简体   繁体   English

如何清除文本文件而不使用groovy删除它

[英]How to clear a text file without deleting it using groovy

I've a text file which I'll be using it to write content.. But every time before I write something to the file, I wish to clear the content without deleting the file.. 我有一个文本文件,我将用它来写内容..但每次我写文件之前,我希望清除内容而不删除文件..

How would I achieve the above? 我如何实现上述目标? Any suggestions? 有什么建议?

使用文本文件,您只需将其设置为空字符串即可。

file.text = ''

I would use the setBytes method on java.io.File and provide it with an empty byte array: 我将java.io.File使用setBytes方法并为其提供一个空字节数组:

file.bytes = new byte[0]

Passing an empty list also works, impressively. 传递一个空列表也很有效。

file.bytes = []

Presumably, you want simply to overwrite the file with new content. 据推测,您只想用新内容覆盖文件。 To do that: 要做到这一点:

def content = ...

new File("test.txt").withWriter { writer ->
    writer.write(content)
}

Note that File.withWriter will do all the usual housekeeping re: open/close file. 请注意, File.withWriter将执行所有常用的内务处理:打开/关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM