NIO extensions for Apache Groovy providing enhanced file system operations and path handling
—
Create and manage various stream types with automatic resource management using closures for safe operation. Provides comprehensive support for readers, writers, input streams, output streams, and print writers.
Create and manage Reader objects for text input with charset support.
/**
* Create a buffered reader for this file
* @param self a Path
* @return a BufferedReader
* @throws IOException if an IOException occurs
*/
BufferedReader newReader(Path self);
/**
* Create a buffered reader for this file, using the specified charset as the encoding
* @param self a Path
* @param charset the charset for this Path
* @return a BufferedReader
* @throws IOException if an IOException occurs
*/
BufferedReader newReader(Path self, String charset);
/**
* Create a new BufferedReader for this file and then passes it into the closure, ensuring the reader is closed after the closure returns
* @param self a file object
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withReader(Path self, Closure<T> closure);
/**
* Create a new BufferedReader for this file using the specified charset and then passes it into the closure, ensuring the reader is closed after the closure returns
* @param self a file object
* @param charset the charset for this input stream
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withReader(Path self, String charset, Closure<T> closure);Usage Examples:
import java.nio.file.Path
import java.nio.file.Paths
Path file = Paths.get("data.txt")
// Create reader (manual resource management)
BufferedReader reader = file.newReader()
try {
String line = reader.readLine()
println line
} finally {
reader.close()
}
// Create reader with charset
BufferedReader reader = file.newReader("UTF-8")
// Automatic resource management with closure
String firstLine = file.withReader { reader ->
reader.readLine()
}
// Process all lines with reader
List<String> lines = file.withReader { reader ->
reader.readLines()
}
// With charset and closure
file.withReader("UTF-8") { reader ->
String line
while ((line = reader.readLine()) != null) {
if (line.startsWith("ERROR")) {
println "Found error: ${line}"
}
}
}Create and manage Writer objects for text output with charset and BOM support.
/**
* Create a buffered writer for this file
* @param self a Path
* @return a BufferedWriter
* @throws IOException if an IOException occurs
*/
BufferedWriter newWriter(Path self);
/**
* Creates a buffered writer for this file, optionally appending to the existing file content
* @param self a Path
* @param append true if data should be appended to the file
* @return a BufferedWriter
* @throws IOException if an IOException occurs
*/
BufferedWriter newWriter(Path self, boolean append);
/**
* Creates a buffered writer for this file without writing a BOM, writing data using the given encoding
* @param self a Path
* @param charset the name of the encoding used to write in this file
* @return a BufferedWriter
* @throws IOException if an IOException occurs
*/
BufferedWriter newWriter(Path self, String charset);
/**
* Helper method to create a buffered writer for a file without writing a BOM
* @param self a Path
* @param charset the name of the encoding used to write in this file
* @param append true if in append mode
* @return a BufferedWriter
* @throws IOException if an IOException occurs
*/
BufferedWriter newWriter(Path self, String charset, boolean append);
/**
* Helper method to create a buffered writer for a file. If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
* the requisite byte order mark is written to the stream before the writer is returned
* @param self a Path
* @param charset the name of the encoding used to write in this file
* @param append true if in append mode
* @param writeBom whether to write a BOM
* @return a BufferedWriter
* @throws IOException if an IOException occurs
*/
BufferedWriter newWriter(Path self, String charset, boolean append, boolean writeBom);
/**
* Creates a new BufferedWriter for this file, passes it to the closure, and ensures the stream is flushed and closed after the closure returns.
* The writer will not write a BOM
* @param self a Path
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withWriter(Path self, Closure<T> closure);
/**
* Creates a new BufferedWriter for this file, passes it to the closure, and ensures the stream is flushed and closed after the closure returns.
* The writer will use the given charset encoding, but will not write a BOM
* @param self a Path
* @param charset the charset used
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withWriter(Path self, String charset, Closure<T> closure);
/**
* Creates a new BufferedWriter for this file, passes it to the closure, and ensures the stream is flushed and closed after the closure returns.
* The writer will use the given charset encoding. If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
* writeBom is true, and the file doesn't already exist, the requisite byte order mark is written to the stream when the writer is created
* @param self a Path
* @param charset the charset used
* @param writeBom whether to write the BOM
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withWriter(Path self, String charset, boolean writeBom, Closure<T> closure);
/**
* Create a new BufferedWriter which will append to this file. The writer is passed to the closure and will be closed before this method returns.
* The writer will use the given charset encoding, but will not write a BOM
* @param self a Path
* @param charset the charset used
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withWriterAppend(Path self, String charset, Closure<T> closure);
/**
* Create a new BufferedWriter which will append to this file. The writer is passed to the closure and will be closed before this method returns.
* The writer will use the given charset encoding. If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
* writeBom is true, and the file doesn't already exist, the requisite byte order mark is written to the stream when the writer is created
* @param self a Path
* @param charset the charset used
* @param writeBom whether to write the BOM
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withWriterAppend(Path self, String charset, boolean writeBom, Closure<T> closure);
/**
* Create a new BufferedWriter for this file in append mode. The writer is passed to the closure and is closed after the closure returns.
* The writer will not write a BOM
* @param self a Path
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withWriterAppend(Path self, Closure<T> closure);Usage Examples:
import java.nio.file.Path
import java.nio.file.Paths
Path outputFile = Paths.get("output.txt")
// Create writer (manual resource management)
BufferedWriter writer = outputFile.newWriter()
try {
writer.write("Hello, World!")
writer.flush()
} finally {
writer.close()
}
// Create writer in append mode
BufferedWriter appendWriter = outputFile.newWriter(true)
// Create writer with charset
BufferedWriter utf8Writer = outputFile.newWriter("UTF-8")
// Create writer with charset and BOM
BufferedWriter bomWriter = outputFile.newWriter("UTF-16LE", false, true)
// Automatic resource management with closure
outputFile.withWriter { writer ->
writer.writeLine("Line 1")
writer.writeLine("Line 2")
}
// With charset
outputFile.withWriter("UTF-8") { writer ->
writer.write("Unicode content: 你好世界")
}
// With charset and BOM
outputFile.withWriter("UTF-16LE", true) { writer ->
writer.write("UTF-16 content with BOM")
}
// Append mode
outputFile.withWriterAppend { writer ->
writer.writeLine("Appended line")
}
// Append with charset
outputFile.withWriterAppend("UTF-8") { writer ->
writer.write("Appended Unicode: こんにちは")
}Create and manage InputStream objects for binary input operations.
/**
* Creates a buffered input stream for this file
* @param self a Path
* @return a BufferedInputStream of the file
* @throws IOException if an IOException occurs
*/
BufferedInputStream newInputStream(Path self);
/**
* Create a data input stream for this file
* @param self a Path
* @return a DataInputStream of the file
* @throws IOException if an IOException occurs
*/
DataInputStream newDataInputStream(Path self);
/**
* Create a new InputStream for this file and passes it into the closure.
* This method ensures the stream is closed after the closure returns
* @param self a Path
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withInputStream(Path self, Closure<T> closure);
/**
* Create a new DataInputStream for this file and passes it into the closure.
* This method ensures the stream is closed after the closure returns
* @param self a Path
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withDataInputStream(Path self, Closure<T> closure);Usage Examples:
import java.nio.file.Path
import java.nio.file.Paths
Path binaryFile = Paths.get("data.bin")
// Create input stream (manual resource management)
BufferedInputStream inputStream = binaryFile.newInputStream()
try {
int byte1 = inputStream.read()
println "First byte: ${byte1}"
} finally {
inputStream.close()
}
// Create data input stream
DataInputStream dataStream = binaryFile.newDataInputStream()
// Automatic resource management with closure
byte[] firstBytes = binaryFile.withInputStream { stream ->
byte[] buffer = new byte[1024]
int bytesRead = stream.read(buffer)
return buffer[0..bytesRead-1]
}
// Process binary data with data input stream
binaryFile.withDataInputStream { dataStream ->
int intValue = dataStream.readInt()
double doubleValue = dataStream.readDouble()
String utf8String = dataStream.readUTF()
println "Int: ${intValue}, Double: ${doubleValue}, String: ${utf8String}"
}
// Copy binary data
Path sourceBinary = Paths.get("source.bin")
Path destBinary = Paths.get("dest.bin")
sourceBinary.withInputStream { input ->
destBinary.withOutputStream { output ->
byte[] buffer = new byte[8192]
int bytesRead
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead)
}
}
}Create and manage OutputStream objects for binary output operations.
/**
* Create a buffered output stream for this file
* @param self a file object
* @return the created OutputStream
* @throws IOException if an IOException occurs
*/
BufferedOutputStream newOutputStream(Path self);
/**
* Creates a new data output stream for this file
* @param self a file object
* @return the created DataOutputStream
* @throws IOException if an IOException occurs
*/
DataOutputStream newDataOutputStream(Path self);
/**
* Creates a new OutputStream for this file and passes it into the closure.
* This method ensures the stream is closed after the closure returns
* @param self a Path
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withOutputStream(Path self, Closure<T> closure);
/**
* Create a new DataOutputStream for this file and passes it into the closure.
* This method ensures the stream is closed after the closure returns
* @param self a Path
* @param closure a closure
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withDataOutputStream(Path self, Closure<T> closure);Usage Examples:
import java.nio.file.Path
import java.nio.file.Paths
Path outputFile = Paths.get("output.bin")
// Create output stream (manual resource management)
BufferedOutputStream outputStream = outputFile.newOutputStream()
try {
outputStream.write([0x48, 0x65, 0x6C, 0x6C, 0x6F] as byte[])
outputStream.flush()
} finally {
outputStream.close()
}
// Create data output stream
DataOutputStream dataStream = outputFile.newDataOutputStream()
// Automatic resource management with closure
outputFile.withOutputStream { stream ->
stream.write("Hello".getBytes())
stream.write([0x00, 0x01, 0x02] as byte[])
}
// Write structured binary data
outputFile.withDataOutputStream { dataStream ->
dataStream.writeInt(42)
dataStream.writeDouble(3.14159)
dataStream.writeUTF("Hello, World!")
dataStream.writeBoolean(true)
}
// Write image data
Path imageFile = Paths.get("generated.png")
imageFile.withOutputStream { stream ->
// Write PNG header
stream.write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] as byte[])
// ... write rest of PNG data
}Create and manage PrintWriter objects for formatted text output.
/**
* Create a new PrintWriter for this file
* @param self a Path
* @return the created PrintWriter
* @throws IOException if an IOException occurs
*/
PrintWriter newPrintWriter(Path self);
/**
* Create a new PrintWriter for this file, using specified charset
* @param self a Path
* @param charset the charset
* @return a PrintWriter
* @throws IOException if an IOException occurs
*/
PrintWriter newPrintWriter(Path self, String charset);
/**
* Create a new PrintWriter for this file which is then passed it into the given closure.
* This method ensures its the writer is closed after the closure returns
* @param self a Path
* @param closure the closure to invoke with the PrintWriter
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withPrintWriter(Path self, Closure<T> closure);
/**
* Create a new PrintWriter with a specified charset for this file.
* The writer is passed to the closure, and will be closed before this method returns
* @param self a Path
* @param charset the charset
* @param closure the closure to invoke with the PrintWriter
* @return the value returned by the closure
* @throws IOException if an IOException occurs
*/
<T> T withPrintWriter(Path self, String charset, Closure<T> closure);Usage Examples:
import java.nio.file.Path
import java.nio.file.Paths
Path reportFile = Paths.get("report.txt")
// Create print writer (manual resource management)
PrintWriter printer = reportFile.newPrintWriter()
try {
printer.println("Report Header")
printer.printf("Value: %d, Percentage: %.2f%%\n", 42, 85.5)
} finally {
printer.close()
}
// Create print writer with charset
PrintWriter utf8Printer = reportFile.newPrintWriter("UTF-8")
// Automatic resource management with closure
reportFile.withPrintWriter { printer ->
printer.println("=== System Report ===")
printer.println("Date: ${new Date()}")
printer.println("Status: OK")
(1..5).each { i ->
printer.printf("Item %d: Value = %d\n", i, i * 10)
}
}
// With charset
reportFile.withPrintWriter("UTF-8") { printer ->
printer.println("Unicode Report: 报告")
printer.println("Japanese: レポート")
printer.println("Arabic: تقرير")
}
// Generate CSV report
Path csvFile = Paths.get("data.csv")
csvFile.withPrintWriter { printer ->
printer.println("Name,Age,City")
def people = [
[name: "Alice", age: 30, city: "New York"],
[name: "Bob", age: 25, city: "London"],
[name: "Charlie", age: 35, city: "Tokyo"]
]
people.each { person ->
printer.printf("%s,%d,%s\n", person.name, person.age, person.city)
}
}Convert Path objects to Groovy's Writable interface for streaming and template operations.
/**
* Converts a Path to a Writable object that can be used for streaming output
* @param self a Path
* @return a Writable object that will write the file contents
*/
Path asWritable(Path self);
/**
* Converts a Path to a Writable object with specified encoding
* @param self a Path
* @param encoding the character encoding to use when reading the file
* @return a Writable object that will write the file contents using the specified encoding
*/
Path asWritable(Path self, String encoding);
/**
* Type conversion method that supports converting Path to various types including Writable
* @param path a Path object
* @param c the target class type
* @return the converted object of type T
*/
<T> T asType(Path path, Class<T> c);Usage Examples:
import java.nio.file.Path
import java.nio.file.Paths
import groovy.lang.Writable
Path templateFile = Paths.get("template.txt")
// Convert to Writable for output streaming
Writable content = templateFile.asWritable()
// Write to another file via Writable
Path outputFile = Paths.get("output.txt")
outputFile.withWriter { writer ->
content.writeTo(writer)
}
// Convert with specific encoding
Writable utf8Content = templateFile.asWritable("UTF-8")
// Use in template engines or streaming contexts
def template = templateFile.asWritable()
System.out.withWriter { writer ->
template.writeTo(writer)
}
// Type conversion to Writable
Writable writable = templateFile.asType(Writable.class)
// Use in Groovy templates
def engine = new groovy.text.SimpleTemplateEngine()
def binding = [name: "World", date: new Date()]
// Template file content can be streamed
templateFile.withReader { reader ->
def template = engine.createTemplate(reader)
def result = template.make(binding)
outputFile.withWriter { writer ->
result.writeTo(writer)
}
}Install with Tessl CLI
npx tessl i tessl/maven-org-codehaus-groovy--groovy-nio