Leer un archivo en Groovy

1. Información general

En este tutorial rápido, exploraremos diferentes formas de leer un archivo en Groovy.

Groovy proporciona formas convenientes de manejar archivos. Nos concentraremos en la clase File , que tiene algunos métodos auxiliares para leer archivos.

Vamos a explorarlos uno por uno en las siguientes secciones.

2. Leer un archivo línea por línea

Hay muchos métodos Groovy IO como readLine y eachLine disponibles para leer archivos línea por línea.

2.1. Usando File.withReader

Comencemos con el método File .withReader . Crea un nuevo BufferedReader debajo de las cubiertas que podemos usar para leer el contenido usando el método readLine .

Por ejemplo, leamos un archivo línea por línea e imprimamos cada línea. También devolveremos el número de líneas:

int readFileLineByLine(String filePath) { File file = new File(filePath) def line, noOfLines = 0; file.withReader { reader -> while ((line = reader.readLine()) != null) { println "${line}" noOfLines++ } } return noOfLines }

Creemos un archivo de texto sin formato fileContent.txt con el siguiente contenido y usémoslo para la prueba:

Line 1 : Hello World!!! Line 2 : This is a file content. Line 3 : String content

Probemos nuestro método de utilidad:

def 'Should return number of lines in File given filePath' () { given: def filePath = "src/main/resources/fileContent.txt" when: def noOfLines = readFile.readFileLineByLine(filePath) then: noOfLines noOfLines instanceof Integer assert noOfLines, 3 } 

El método withReader también se puede utilizar con un parámetro de juego de caracteres como UTF-8 o ASCII para leer archivos codificados . Veamos un ejemplo:

new File("src/main/resources/utf8Content.html").withReader('UTF-8') { reader -> def line while ((line = reader.readLine()) != null) { println "${line}" } }

2.2. Usando File.eachLine

También podemos usar el método eachLine :

new File("src/main/resources/fileContent.txt").eachLine { line -> println line } 

2.3. Usando File.newInputStream con InputStream.eachLine

Veamos cómo podemos usar InputStream con cada línea para leer un archivo:

def is = new File("src/main/resources/fileContent.txt").newInputStream() is.eachLine { println it } is.close()

Cuando usamos el método newInputStream , tenemos que lidiar con el cierre de InputStream .

Si usamos el método withInputStream en su lugar, manejará el cierre de InputStream por nosotros:

new File("src/main/resources/fileContent.txt").withInputStream { stream -> stream.eachLine { line -> println line } }

3. Leer un archivo en una lista

A veces necesitamos leer el contenido de un archivo en una lista de líneas.

3.1. Usando File.readLines

Para esto, podemos usar el método readLines que lee el archivo en una lista de cadenas .

Echemos un vistazo rápido a un ejemplo que lee el contenido del archivo y devuelve una lista de líneas:

List readFileInList(String filePath) { File file = new File(filePath) def lines = file.readLines() return lines }

Escribamos una prueba rápida usando fileContent.txt :

def 'Should return File Content in list of lines given filePath' () { given: def filePath = "src/main/resources/fileContent.txt" when: def lines = readFile.readFileInList(filePath) then: lines lines instanceof List assert lines.size(), 3 }

3.2. Usando File.collect

También podemos leer el contenido del archivo en una lista de cadenas utilizando la API de recopilación :

def list = new File("src/main/resources/fileContent.txt").collect {it} 

3.3. Usando el como operador

Incluso podemos aprovechar el operador as para leer el contenido del archivo en una matriz de cadenas :

def array = new File("src/main/resources/fileContent.txt") as String[]

4. Leer un archivo en una sola cadena

4.1. Using File.text

We can read an entire file into a single String simply by using the text property of the File class.

Let's have a look at an example:

String readFileString(String filePath) { File file = new File(filePath) String fileContent = file.text return fileContent } 

Let's verify this with a unit test:

def 'Should return file content in string given filePath' () { given: def filePath = "src/main/resources/fileContent.txt" when: def fileContent = readFile.readFileString(filePath) then: fileContent fileContent instanceof String fileContent.contains("""Line 1 : Hello World!!! Line 2 : This is a file content. Line 3 : String content""") }

4.2. Using File.getText

If we use the getTest(charset) method, we can read the content of an encoded file into a String by providing a charset parameter like UTF-8 or ASCII:

String readFileStringWithCharset(String filePath) { File file = new File(filePath) String utf8Content = file.getText("UTF-8") return utf8Content }

Let's create an HTML file with UTF-8 content named utf8Content.html for the unit testing:

ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ ᛋᚳᛖᚪᛚ᛫ᚦᛖᚪᚻ᛫ᛗᚪᚾᚾᚪ᛫ᚷᛖᚻᚹᛦᛚᚳ᛫ᛗᛁᚳᛚᚢᚾ᛫ᚻᛦᛏ᛫ᛞᚫᛚᚪᚾ ᚷᛁᚠ᛫ᚻᛖ᛫ᚹᛁᛚᛖ᛫ᚠᚩᚱ᛫ᛞᚱᛁᚻᛏᚾᛖ᛫ᛞᚩᛗᛖᛋ᛫ᚻᛚᛇᛏᚪᚾ 

Let's see the unit test:

def 'Should return UTF-8 encoded file content in string given filePath' () { given: def filePath = "src/main/resources/utf8Content.html" when: def encodedContent = readFile.readFileStringWithCharset(filePath) then: encodedContent encodedContent instanceof String }

5. Reading a Binary File with File.bytes

Groovy facilita la lectura de archivos binarios o sin texto. Al usar la propiedad bytes , podemos obtener el contenido del archivo como una matriz de bytes :

byte[] readBinaryFile(String filePath) { File file = new File(filePath) byte[] binaryContent = file.bytes return binaryContent }

Usaremos un archivo de imagen png, sample.png , con el siguiente contenido para la prueba unitaria:

Veamos la prueba unitaria:

def 'Should return binary file content in byte array given filePath' () { given: def filePath = "src/main/resources/sample.png" when: def binaryContent = readFile.readBinaryFile(filePath) then: binaryContent binaryContent instanceof byte[] binaryContent.length == 329 }

6. Conclusión

En este tutorial rápido, hemos visto diferentes formas de leer un archivo en Groovy usando varios métodos de la clase File junto con BufferedReader y InputStream .

El código fuente completo de estas implementaciones y casos de prueba unitaria se puede encontrar en el proyecto GitHub.