简体   繁体   English

如何使用Groovy创建文本文件?

[英]How to create text file using Groovy?

I am trying to create a new text file using the below lines of Groovy code in Soap UI but I do not see the file is created 我试图在Soap UI中使用以下Groovy代码行创建一个新的文本文件,但我没有看到该文件已创建

import java.io.File 
def newFile = new File("C:/Users/ramus/Documents/Jars/test.txt")

Could you please help me in understanding on what is wrong with the above lines of code? 能否帮助我理解上面代码行有什么问题?

new File(path) means create pointer to file or directory with selected path. new File(path)表示创建指向具有所选路径的文件或目录的指针。 Using this pointer you can do anything what you want create, read, append etc. If you wish to only create file on drive you can do: 使用此指针,您可以执行任何您想要创建,读取,追加等操作。如果您只想在驱动器上创建文件,您可以执行以下操作:

def newFile = new File("C:/Users/ramus/Documents/Jars/test.txt")
newFile.createNewFile() 

Just an addition to the accepted answer--if you want to create a file with content, you can do this: 只是对已接受答案的补充 - 如果要创建包含内容的文件,可以执行以下操作:

new File("C:/Users/ramus/Documents/Jars/test.txt").text = "Test text file content"

This particular feature is one of my favorite parts of groovy, you can even append to a file with += 这个特殊功能是我最喜欢的groovy部分之一,你甚至可以附加到+ =的文件

You can also use: 您还可以使用:

def newFile = new File("new.txt")
newFile.write("text to be added to the new file")

If you want to always make sure it's a new file, ie overwrite any existing file, you can use: 如果您想要始终确保它是一个新文件,即覆盖任何现有文件,您可以使用:

//...Create file... 

file.newWriter.withWriter { it << "some text" }

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

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