Srinivasan Ramu
Srinivasan Ramu

Reputation: 1063

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

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?

Upvotes: 14

Views: 70249

Answers (5)

Rahul Desai
Rahul Desai

Reputation: 309

Initialise your file:

def yourFile = new File("yourFilePath.txt")

Delete any record of already existing file. This works even if there is no existing file.

yourFile.delete()

And finally, Create new file.

yourFile.createNewFile()

To add content to your file, you can use:

yourFile.text="Text content"

At this step your file contains : "Text content"

yourFile.append=" appended to my file"

At this step your file contains : "Text content appended to my file"

yourFile.text="New content of your file"

At this step your file contains : "New content of your file"

Upvotes: 12

Adam Taylor
Adam Taylor

Reputation: 56

If you want to always make sure it's a new file, i.e. overwrite any existing file, you can use:

//...Create file... 

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

Upvotes: 3

You can also use:

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

Upvotes: 7

Bill K
Bill K

Reputation: 62769

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 +=

Upvotes: 20

Evgeny Smirnov
Evgeny Smirnov

Reputation: 3016

new File(path) means create pointer to file or directory with selected 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() 

Upvotes: 24

Related Questions