Skip to content

Instantly share code, notes, and snippets.

@js1972
Created May 16, 2014 07:42
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save js1972/22d9c24a62776d8e85cc to your computer and use it in GitHub Desktop.
Save js1972/22d9c24a62776d8e85cc to your computer and use it in GitHub Desktop.
How to write content to a new file (overwrite if already existing) in Groovy.
//
// Write the mock request payload to a file for checking later...
// newWrite() is the important it to ensure you get a *new* file each time.
//
def filename = "C:\\MyScratchFolder\\soapUI projects\\Testing\\procon\\mock_po_activity_request.xml"
def file = new File(filename)
def w = file.newWriter()
w << mockRequest.requestContent
w.close()
@llehtinen
Copy link

This helped me today :) Make it ever groovier (closes writer for you):

file.newWriter().withWriter {
  w << mockRequest.requestContent
}

@ruoguluo
Copy link

thank you!

@esmiralha
Copy link

Small typo above:

file.newWriter().withWriter { w ->
  w << mockRequest.requestContent
}

@ddskolla
Copy link

ddskolla commented Sep 8, 2016

Yes yes yes, Thank You !

@mangan77
Copy link

Thanks a lot!

@martinkbrown
Copy link

Works. Thanks!

@DenverKen
Copy link

I"m a Groovy newb and this was really helpful to me, thanks!

@gezerk
Copy link

gezerk commented Jan 6, 2018

Nice! This was a great help. The comments were super useful too.

@fadyboy
Copy link

fadyboy commented Mar 28, 2018

This helped me too, thanks a lot

@sateesharv
Copy link

Thanks

@stevetrottier
Copy link

stevetrottier commented Jul 27, 2022

Thank you! For future readers who get here from a web search (like I did), I think it's unnecessary to use both newWriter and withWriter in the examples above. Using just withWriter will create the file if it doesn't exist yet, or replace the existing content if it already exists:

file.withWriter { w ->
  w << mockRequest.requestContent
}

Similarly, using withWriterAppend will create the file if it doesn't exist (just like above), or append to the existing content if it already exists:

file.withWriterAppend { w ->
  w << mockRequest.requestContent
}

Note that when using withWriter or withWriterAppend you can also specify a specific character encoding for the writer, and doing so is recommended as a best practice.

file.withWriter('UTF-8') { w ->
  w << mockRequest.requestContent
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment