Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create text file using Groovy?

Tags:

file

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?

like image 366
Srinivasan Ramu Avatar asked Feb 01 '18 15:02

Srinivasan Ramu


People also ask

How do I save a Groovy script?

To save a Groovy script that is currently open in the Groovy editor: From the Tools Main menu select Groovy > Save Script or Save Script As.

How do I create a folder in Groovy?

Creating a Directory If you want to create a new directory you can use the mkdir function of the File class.

What File type is Groovy?

What is a GROOVY file? A GROOVY file is a source code file written in the Groovy programming language. Code written inside a GROOVY file is similar to the object-oriented language Java, that makes it easy for design and development of applications.


3 Answers

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

like image 60
Bill K Avatar answered Sep 29 '22 20:09

Bill K


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"

like image 44
Rahul Desai Avatar answered Sep 29 '22 20:09

Rahul Desai


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() 
like image 30
Evgeny Smirnov Avatar answered Sep 29 '22 20:09

Evgeny Smirnov