Cómo leer un archivo en Groovy en una cadena?


Necesito leer un archivo del sistema de archivos y cargar todo el contenido en una cadena en un controlador groovy, ¿cuál es la forma más fácil de hacerlo?

 256
Author: raffian, 2011-10-11

6 answers

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

Si necesita especificar la codificación de caracteres, utilice lo siguiente:

String fileContents = new File('/path/to/file').getText('UTF-8')
 419
Author: Dónal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-16 14:44:28

El camino más corto es de hecho justo

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

Pero en este caso no tiene control sobre cómo los bytes en el archivo se interpretan como caracteres. AFAIK groovy intenta adivinar la codificación aquí mirando el contenido del archivo.

Si desea una codificación de caracteres específica, puede especificar un nombre de conjunto de caracteres con

String fileContents = new File('/path/to/file').getText('UTF-8')

Ver API docs on File.getText(String) para más información.

 71
Author: jaetzold,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-10 11:42:00

Una ligera variación...

new File('/path/to/file').eachLine { line ->
  println line
}
 40
Author: linus1412,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-31 08:01:57

La forma más fácil sería

new File(filename).getText()

Lo que significa que podrías hacer:

new File(filename).text

 11
Author: Reverend Gonzo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-14 10:06:58

En mi caso new File() no funciona, causa un FileNotFoundException cuando se ejecuta en un trabajo de canalización Jenkins. El siguiente código resolvió esto, y es aún más fácil en mi opinión:

def fileContents = readFile "path/to/file"

Todavía no entiendo esta diferencia completamente, pero tal vez ayude a alguien más con el mismo problema. Posiblemente la excepción fue causada porque new File() crea un archivo en el sistema que ejecuta el código groovy, que era un sistema diferente al que contiene el archivo que quería leer.

 3
Author: P Kuijpers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-31 11:04:39

Aquí puedes encontrar otra forma de hacer lo mismo.

Leer archivo.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();

Leer el archivo completo.

File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();

Leer línea de archivo Línea Bye.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
for (def i=0;i<=30;i++) // specify how many line need to read eg.. 30
{
 log.info file1.readLines().get(i)

}

Crea un nuevo archivo.

new File("C:\Temp\FileName.txt").createNewFile();
 0
Author: shashi singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-26 20:13:57