Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file in Groovy into a string?

Tags:

file

groovy

I need to read a file from the file system and load the entire contents into a string in a groovy controller, what's the easiest way to do that?

like image 507
raffian Avatar asked Oct 11 '11 16:10

raffian


People also ask

How do I read a string in Groovy?

String IndexingThe individual character in a string can be accessed by its position. This is given by an index position. String indices start at zero and end at one less than the length of the string. Groovy also permits negative indices to count back from the end of the string.

How do I set the path of a file in Groovy?

Since the path changes machine to machine, you need to use a variable / project level property, say BASE_DIRECTORY, set this value according to machine, here "/home/vishalpachupute" and rest of the path maintain the directory structure for the resources being used. Regards, Rao.


1 Answers

String fileContents = new File('/path/to/file').text 

If you need to specify the character encoding, use the following instead:

String fileContents = new File('/path/to/file').getText('UTF-8') 
like image 121
Dónal Avatar answered Sep 21 '22 15:09

Dónal