Lendo um arquivo no Groovy

Lendo um arquivo no Groovy

1. Visão geral

Neste tutorial rápido, exploraremos diferentes maneiras de ler um arquivo emGroovy.

O Groovy fornece maneiras convenientes de lidar com arquivos. Vamos nos concentrar na classeFile, que tem alguns métodos auxiliares para ler arquivos.

Vamos explorá-los um por um nas seções a seguir.

2. Lendo umFile linha por linha

Existem muitosGroovy IO methods comoreadLineeeachLine disponíveis para leitura de arquivos linha por linha.

2.1. UsandoFile.withReader

Vamos começar com o métodohttp://docs.groovy-lang.org/next/html/groovy-jdk/java/io/File.html.withReader. It creates a new BufferedReader under the covers that we can use to read the contents using the readLine method.

Por exemplo, vamos ler um arquivo linha por linha e imprimir cada linha. Também retornaremos o número de linhas:

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
}

Vamos criar um arquivo de texto simplesfileContent.txt com o seguinte conteúdo e usá-lo para o teste:

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

Vamos testar nosso método utilitário:

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
}

The withReader method can also be used with a charset parameter like UTF-8 or ASCII to read encoded files. Vamos ver um exemplo:

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

2.2. UsandoFile.eachLine

Também podemos usar o métodoeachLine:

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

2.3. UsandoFile.newInputStream comInputStream.eachLine

Vamos ver como podemos usarInputStream comeachLine para ler um arquivo:

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

When we use the newInputStream method, we have to deal with closing the InputStream.

Se usarmos o métodowithInputStream, ele fechará oInputStream para nós:

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

3. Lendo umFile em umList

Às vezes, precisamos ler o conteúdo de um arquivo em uma lista de linhas.

3.1. UsandoFile.readLines

Para isso, podemos usar o métodoreadLines que lê o arquivo emList deStrings.

Vamos dar uma olhada rápida em um exemplo que lê o conteúdo do arquivo e retorna uma lista de linhas:

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

Vamos escrever um teste rápido usandofileContent.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. UsandoFile.collect

Também podemos ler o conteúdo do arquivo emList deStrings usando a APIcollect:

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

3.3. Usando o operadoras

Podemos até mesmo aproveitar o operadoras para ler o conteúdo do arquivo em uma matrizString:

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

4. Lendo umFile em um únicoString

4.1. UsandoFile.text

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

Vamos dar uma olhada em um exemplo:

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

Vamos verificar isso com um teste de unidade:

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. UsandoFile.getText

Se usarmos o métodogetTest(charset), podemos ler o conteúdo de um arquivo codificado emString fornecendo um parâmetro de conjunto de caracteres como UTF-8 ou ASCII:

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

Vamos criar um arquivo HTML com conteúdo UTF-8 denominadoutf8Content.html para o teste de unidade:

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

Vamos ver o teste de unidade:

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. Lendo um arquivo binário comFile.bytes

O Groovy facilita a leitura de arquivos não texto ou binários. By using the bytes property, we can get the contents of the File as a byte array:

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

Usaremos um arquivo de imagem png,sample.png, com o seguinte conteúdo para o teste de unidade:

image

 

Vamos ver o teste de unidade:

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. Conclusão

Neste tutorial rápido, vimos diferentes maneiras de ler um arquivo no Groovy usando vários métodos da classeFile junto comBufferedReadereInputStream.

O código-fonte completo dessas implementações e casos de teste de unidade pode ser encontrado no projetoGitHub.