Read file
Reading a file in Groovy, a dynamic language that runs on the Java platform, is quite straightforward due to Groovy's simplified syntax and powerful features. Here are a couple of common methods you can use to read a file in Groovy:
1. Using File.text
This method is very convenient for reading small files as it directly returns the content of the file as a String.
def fileContent = new File('path/to/file.txt').text
println(fileContent)
2. Using File.eachLine
If you're dealing with larger files or if you want to process the file line by line, you can use eachLine
. This method allows you to handle each line individually, which can be useful for memory management.
new File('path/to/file.txt').eachLine { line ->
println(line)
}
3. Using InputStream
For binary files or when you need more control over the reading process (like specifying a buffer size), you can use an InputStream.
new File('path/to/file.txt').withInputStream { stream ->
byte[] buffer = new byte[1024]
int bytesRead
while ((bytesRead = stream.read(buffer)) != -1) {
// process buffer
println(new String(buffer, 0, bytesRead))
}
}
4. Using BufferedReader
This is another way to read large text files efficiently. BufferedReader
provides a convenient way to read text from a character input stream.
new File('path/to/file.txt').withReader { reader ->
reader.eachLine { line ->
println(line)
}
}
Each of these methods has its own use cases depending on your specific requirements, such as the size of the file and the type of processing needed.