0
# Stream Operations
1
2
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.
3
4
## Capabilities
5
6
### Reader Operations
7
8
Create and manage Reader objects for text input with charset support.
9
10
```java { .api }
11
/**
12
* Create a buffered reader for this file
13
* @param self a Path
14
* @return a BufferedReader
15
* @throws IOException if an IOException occurs
16
*/
17
BufferedReader newReader(Path self);
18
19
/**
20
* Create a buffered reader for this file, using the specified charset as the encoding
21
* @param self a Path
22
* @param charset the charset for this Path
23
* @return a BufferedReader
24
* @throws IOException if an IOException occurs
25
*/
26
BufferedReader newReader(Path self, String charset);
27
28
/**
29
* Create a new BufferedReader for this file and then passes it into the closure, ensuring the reader is closed after the closure returns
30
* @param self a file object
31
* @param closure a closure
32
* @return the value returned by the closure
33
* @throws IOException if an IOException occurs
34
*/
35
<T> T withReader(Path self, Closure<T> closure);
36
37
/**
38
* 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
39
* @param self a file object
40
* @param charset the charset for this input stream
41
* @param closure a closure
42
* @return the value returned by the closure
43
* @throws IOException if an IOException occurs
44
*/
45
<T> T withReader(Path self, String charset, Closure<T> closure);
46
```
47
48
**Usage Examples:**
49
50
```groovy
51
import java.nio.file.Path
52
import java.nio.file.Paths
53
54
Path file = Paths.get("data.txt")
55
56
// Create reader (manual resource management)
57
BufferedReader reader = file.newReader()
58
try {
59
String line = reader.readLine()
60
println line
61
} finally {
62
reader.close()
63
}
64
65
// Create reader with charset
66
BufferedReader reader = file.newReader("UTF-8")
67
68
// Automatic resource management with closure
69
String firstLine = file.withReader { reader ->
70
reader.readLine()
71
}
72
73
// Process all lines with reader
74
List<String> lines = file.withReader { reader ->
75
reader.readLines()
76
}
77
78
// With charset and closure
79
file.withReader("UTF-8") { reader ->
80
String line
81
while ((line = reader.readLine()) != null) {
82
if (line.startsWith("ERROR")) {
83
println "Found error: ${line}"
84
}
85
}
86
}
87
```
88
89
### Writer Operations
90
91
Create and manage Writer objects for text output with charset and BOM support.
92
93
```java { .api }
94
/**
95
* Create a buffered writer for this file
96
* @param self a Path
97
* @return a BufferedWriter
98
* @throws IOException if an IOException occurs
99
*/
100
BufferedWriter newWriter(Path self);
101
102
/**
103
* Creates a buffered writer for this file, optionally appending to the existing file content
104
* @param self a Path
105
* @param append true if data should be appended to the file
106
* @return a BufferedWriter
107
* @throws IOException if an IOException occurs
108
*/
109
BufferedWriter newWriter(Path self, boolean append);
110
111
/**
112
* Creates a buffered writer for this file without writing a BOM, writing data using the given encoding
113
* @param self a Path
114
* @param charset the name of the encoding used to write in this file
115
* @return a BufferedWriter
116
* @throws IOException if an IOException occurs
117
*/
118
BufferedWriter newWriter(Path self, String charset);
119
120
/**
121
* Helper method to create a buffered writer for a file without writing a BOM
122
* @param self a Path
123
* @param charset the name of the encoding used to write in this file
124
* @param append true if in append mode
125
* @return a BufferedWriter
126
* @throws IOException if an IOException occurs
127
*/
128
BufferedWriter newWriter(Path self, String charset, boolean append);
129
130
/**
131
* Helper method to create a buffered writer for a file. If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
132
* the requisite byte order mark is written to the stream before the writer is returned
133
* @param self a Path
134
* @param charset the name of the encoding used to write in this file
135
* @param append true if in append mode
136
* @param writeBom whether to write a BOM
137
* @return a BufferedWriter
138
* @throws IOException if an IOException occurs
139
*/
140
BufferedWriter newWriter(Path self, String charset, boolean append, boolean writeBom);
141
142
/**
143
* Creates a new BufferedWriter for this file, passes it to the closure, and ensures the stream is flushed and closed after the closure returns.
144
* The writer will not write a BOM
145
* @param self a Path
146
* @param closure a closure
147
* @return the value returned by the closure
148
* @throws IOException if an IOException occurs
149
*/
150
<T> T withWriter(Path self, Closure<T> closure);
151
152
/**
153
* Creates a new BufferedWriter for this file, passes it to the closure, and ensures the stream is flushed and closed after the closure returns.
154
* The writer will use the given charset encoding, but will not write a BOM
155
* @param self a Path
156
* @param charset the charset used
157
* @param closure a closure
158
* @return the value returned by the closure
159
* @throws IOException if an IOException occurs
160
*/
161
<T> T withWriter(Path self, String charset, Closure<T> closure);
162
163
/**
164
* Creates a new BufferedWriter for this file, passes it to the closure, and ensures the stream is flushed and closed after the closure returns.
165
* The writer will use the given charset encoding. If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
166
* 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
167
* @param self a Path
168
* @param charset the charset used
169
* @param writeBom whether to write the BOM
170
* @param closure a closure
171
* @return the value returned by the closure
172
* @throws IOException if an IOException occurs
173
*/
174
<T> T withWriter(Path self, String charset, boolean writeBom, Closure<T> closure);
175
176
/**
177
* 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.
178
* The writer will use the given charset encoding, but will not write a BOM
179
* @param self a Path
180
* @param charset the charset used
181
* @param closure a closure
182
* @return the value returned by the closure
183
* @throws IOException if an IOException occurs
184
*/
185
<T> T withWriterAppend(Path self, String charset, Closure<T> closure);
186
187
/**
188
* 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.
189
* The writer will use the given charset encoding. If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias),
190
* 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
191
* @param self a Path
192
* @param charset the charset used
193
* @param writeBom whether to write the BOM
194
* @param closure a closure
195
* @return the value returned by the closure
196
* @throws IOException if an IOException occurs
197
*/
198
<T> T withWriterAppend(Path self, String charset, boolean writeBom, Closure<T> closure);
199
200
/**
201
* Create a new BufferedWriter for this file in append mode. The writer is passed to the closure and is closed after the closure returns.
202
* The writer will not write a BOM
203
* @param self a Path
204
* @param closure a closure
205
* @return the value returned by the closure
206
* @throws IOException if an IOException occurs
207
*/
208
<T> T withWriterAppend(Path self, Closure<T> closure);
209
```
210
211
**Usage Examples:**
212
213
```groovy
214
import java.nio.file.Path
215
import java.nio.file.Paths
216
217
Path outputFile = Paths.get("output.txt")
218
219
// Create writer (manual resource management)
220
BufferedWriter writer = outputFile.newWriter()
221
try {
222
writer.write("Hello, World!")
223
writer.flush()
224
} finally {
225
writer.close()
226
}
227
228
// Create writer in append mode
229
BufferedWriter appendWriter = outputFile.newWriter(true)
230
231
// Create writer with charset
232
BufferedWriter utf8Writer = outputFile.newWriter("UTF-8")
233
234
// Create writer with charset and BOM
235
BufferedWriter bomWriter = outputFile.newWriter("UTF-16LE", false, true)
236
237
// Automatic resource management with closure
238
outputFile.withWriter { writer ->
239
writer.writeLine("Line 1")
240
writer.writeLine("Line 2")
241
}
242
243
// With charset
244
outputFile.withWriter("UTF-8") { writer ->
245
writer.write("Unicode content: 你好世界")
246
}
247
248
// With charset and BOM
249
outputFile.withWriter("UTF-16LE", true) { writer ->
250
writer.write("UTF-16 content with BOM")
251
}
252
253
// Append mode
254
outputFile.withWriterAppend { writer ->
255
writer.writeLine("Appended line")
256
}
257
258
// Append with charset
259
outputFile.withWriterAppend("UTF-8") { writer ->
260
writer.write("Appended Unicode: こんにちは")
261
}
262
```
263
264
### Input Stream Operations
265
266
Create and manage InputStream objects for binary input operations.
267
268
```java { .api }
269
/**
270
* Creates a buffered input stream for this file
271
* @param self a Path
272
* @return a BufferedInputStream of the file
273
* @throws IOException if an IOException occurs
274
*/
275
BufferedInputStream newInputStream(Path self);
276
277
/**
278
* Create a data input stream for this file
279
* @param self a Path
280
* @return a DataInputStream of the file
281
* @throws IOException if an IOException occurs
282
*/
283
DataInputStream newDataInputStream(Path self);
284
285
/**
286
* Create a new InputStream for this file and passes it into the closure.
287
* This method ensures the stream is closed after the closure returns
288
* @param self a Path
289
* @param closure a closure
290
* @return the value returned by the closure
291
* @throws IOException if an IOException occurs
292
*/
293
<T> T withInputStream(Path self, Closure<T> closure);
294
295
/**
296
* Create a new DataInputStream for this file and passes it into the closure.
297
* This method ensures the stream is closed after the closure returns
298
* @param self a Path
299
* @param closure a closure
300
* @return the value returned by the closure
301
* @throws IOException if an IOException occurs
302
*/
303
<T> T withDataInputStream(Path self, Closure<T> closure);
304
```
305
306
**Usage Examples:**
307
308
```groovy
309
import java.nio.file.Path
310
import java.nio.file.Paths
311
312
Path binaryFile = Paths.get("data.bin")
313
314
// Create input stream (manual resource management)
315
BufferedInputStream inputStream = binaryFile.newInputStream()
316
try {
317
int byte1 = inputStream.read()
318
println "First byte: ${byte1}"
319
} finally {
320
inputStream.close()
321
}
322
323
// Create data input stream
324
DataInputStream dataStream = binaryFile.newDataInputStream()
325
326
// Automatic resource management with closure
327
byte[] firstBytes = binaryFile.withInputStream { stream ->
328
byte[] buffer = new byte[1024]
329
int bytesRead = stream.read(buffer)
330
return buffer[0..bytesRead-1]
331
}
332
333
// Process binary data with data input stream
334
binaryFile.withDataInputStream { dataStream ->
335
int intValue = dataStream.readInt()
336
double doubleValue = dataStream.readDouble()
337
String utf8String = dataStream.readUTF()
338
339
println "Int: ${intValue}, Double: ${doubleValue}, String: ${utf8String}"
340
}
341
342
// Copy binary data
343
Path sourceBinary = Paths.get("source.bin")
344
Path destBinary = Paths.get("dest.bin")
345
346
sourceBinary.withInputStream { input ->
347
destBinary.withOutputStream { output ->
348
byte[] buffer = new byte[8192]
349
int bytesRead
350
while ((bytesRead = input.read(buffer)) != -1) {
351
output.write(buffer, 0, bytesRead)
352
}
353
}
354
}
355
```
356
357
### Output Stream Operations
358
359
Create and manage OutputStream objects for binary output operations.
360
361
```java { .api }
362
/**
363
* Create a buffered output stream for this file
364
* @param self a file object
365
* @return the created OutputStream
366
* @throws IOException if an IOException occurs
367
*/
368
BufferedOutputStream newOutputStream(Path self);
369
370
/**
371
* Creates a new data output stream for this file
372
* @param self a file object
373
* @return the created DataOutputStream
374
* @throws IOException if an IOException occurs
375
*/
376
DataOutputStream newDataOutputStream(Path self);
377
378
/**
379
* Creates a new OutputStream for this file and passes it into the closure.
380
* This method ensures the stream is closed after the closure returns
381
* @param self a Path
382
* @param closure a closure
383
* @return the value returned by the closure
384
* @throws IOException if an IOException occurs
385
*/
386
<T> T withOutputStream(Path self, Closure<T> closure);
387
388
/**
389
* Create a new DataOutputStream for this file and passes it into the closure.
390
* This method ensures the stream is closed after the closure returns
391
* @param self a Path
392
* @param closure a closure
393
* @return the value returned by the closure
394
* @throws IOException if an IOException occurs
395
*/
396
<T> T withDataOutputStream(Path self, Closure<T> closure);
397
```
398
399
**Usage Examples:**
400
401
```groovy
402
import java.nio.file.Path
403
import java.nio.file.Paths
404
405
Path outputFile = Paths.get("output.bin")
406
407
// Create output stream (manual resource management)
408
BufferedOutputStream outputStream = outputFile.newOutputStream()
409
try {
410
outputStream.write([0x48, 0x65, 0x6C, 0x6C, 0x6F] as byte[])
411
outputStream.flush()
412
} finally {
413
outputStream.close()
414
}
415
416
// Create data output stream
417
DataOutputStream dataStream = outputFile.newDataOutputStream()
418
419
// Automatic resource management with closure
420
outputFile.withOutputStream { stream ->
421
stream.write("Hello".getBytes())
422
stream.write([0x00, 0x01, 0x02] as byte[])
423
}
424
425
// Write structured binary data
426
outputFile.withDataOutputStream { dataStream ->
427
dataStream.writeInt(42)
428
dataStream.writeDouble(3.14159)
429
dataStream.writeUTF("Hello, World!")
430
dataStream.writeBoolean(true)
431
}
432
433
// Write image data
434
Path imageFile = Paths.get("generated.png")
435
imageFile.withOutputStream { stream ->
436
// Write PNG header
437
stream.write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] as byte[])
438
// ... write rest of PNG data
439
}
440
```
441
442
### Print Writer Operations
443
444
Create and manage PrintWriter objects for formatted text output.
445
446
```java { .api }
447
/**
448
* Create a new PrintWriter for this file
449
* @param self a Path
450
* @return the created PrintWriter
451
* @throws IOException if an IOException occurs
452
*/
453
PrintWriter newPrintWriter(Path self);
454
455
/**
456
* Create a new PrintWriter for this file, using specified charset
457
* @param self a Path
458
* @param charset the charset
459
* @return a PrintWriter
460
* @throws IOException if an IOException occurs
461
*/
462
PrintWriter newPrintWriter(Path self, String charset);
463
464
/**
465
* Create a new PrintWriter for this file which is then passed it into the given closure.
466
* This method ensures its the writer is closed after the closure returns
467
* @param self a Path
468
* @param closure the closure to invoke with the PrintWriter
469
* @return the value returned by the closure
470
* @throws IOException if an IOException occurs
471
*/
472
<T> T withPrintWriter(Path self, Closure<T> closure);
473
474
/**
475
* Create a new PrintWriter with a specified charset for this file.
476
* The writer is passed to the closure, and will be closed before this method returns
477
* @param self a Path
478
* @param charset the charset
479
* @param closure the closure to invoke with the PrintWriter
480
* @return the value returned by the closure
481
* @throws IOException if an IOException occurs
482
*/
483
<T> T withPrintWriter(Path self, String charset, Closure<T> closure);
484
```
485
486
**Usage Examples:**
487
488
```groovy
489
import java.nio.file.Path
490
import java.nio.file.Paths
491
492
Path reportFile = Paths.get("report.txt")
493
494
// Create print writer (manual resource management)
495
PrintWriter printer = reportFile.newPrintWriter()
496
try {
497
printer.println("Report Header")
498
printer.printf("Value: %d, Percentage: %.2f%%\n", 42, 85.5)
499
} finally {
500
printer.close()
501
}
502
503
// Create print writer with charset
504
PrintWriter utf8Printer = reportFile.newPrintWriter("UTF-8")
505
506
// Automatic resource management with closure
507
reportFile.withPrintWriter { printer ->
508
printer.println("=== System Report ===")
509
printer.println("Date: ${new Date()}")
510
printer.println("Status: OK")
511
512
(1..5).each { i ->
513
printer.printf("Item %d: Value = %d\n", i, i * 10)
514
}
515
}
516
517
// With charset
518
reportFile.withPrintWriter("UTF-8") { printer ->
519
printer.println("Unicode Report: 报告")
520
printer.println("Japanese: レポート")
521
printer.println("Arabic: تقرير")
522
}
523
524
// Generate CSV report
525
Path csvFile = Paths.get("data.csv")
526
csvFile.withPrintWriter { printer ->
527
printer.println("Name,Age,City")
528
529
def people = [
530
[name: "Alice", age: 30, city: "New York"],
531
[name: "Bob", age: 25, city: "London"],
532
[name: "Charlie", age: 35, city: "Tokyo"]
533
]
534
535
people.each { person ->
536
printer.printf("%s,%d,%s\n", person.name, person.age, person.city)
537
}
538
}
539
```
540
541
### Writable Conversion
542
543
Convert Path objects to Groovy's Writable interface for streaming and template operations.
544
545
```java { .api }
546
/**
547
* Converts a Path to a Writable object that can be used for streaming output
548
* @param self a Path
549
* @return a Writable object that will write the file contents
550
*/
551
Path asWritable(Path self);
552
553
/**
554
* Converts a Path to a Writable object with specified encoding
555
* @param self a Path
556
* @param encoding the character encoding to use when reading the file
557
* @return a Writable object that will write the file contents using the specified encoding
558
*/
559
Path asWritable(Path self, String encoding);
560
561
/**
562
* Type conversion method that supports converting Path to various types including Writable
563
* @param path a Path object
564
* @param c the target class type
565
* @return the converted object of type T
566
*/
567
<T> T asType(Path path, Class<T> c);
568
```
569
570
**Usage Examples:**
571
572
```groovy
573
import java.nio.file.Path
574
import java.nio.file.Paths
575
import groovy.lang.Writable
576
577
Path templateFile = Paths.get("template.txt")
578
579
// Convert to Writable for output streaming
580
Writable content = templateFile.asWritable()
581
582
// Write to another file via Writable
583
Path outputFile = Paths.get("output.txt")
584
outputFile.withWriter { writer ->
585
content.writeTo(writer)
586
}
587
588
// Convert with specific encoding
589
Writable utf8Content = templateFile.asWritable("UTF-8")
590
591
// Use in template engines or streaming contexts
592
def template = templateFile.asWritable()
593
System.out.withWriter { writer ->
594
template.writeTo(writer)
595
}
596
597
// Type conversion to Writable
598
Writable writable = templateFile.asType(Writable.class)
599
600
// Use in Groovy templates
601
def engine = new groovy.text.SimpleTemplateEngine()
602
def binding = [name: "World", date: new Date()]
603
604
// Template file content can be streamed
605
templateFile.withReader { reader ->
606
def template = engine.createTemplate(reader)
607
def result = template.make(binding)
608
609
outputFile.withWriter { writer ->
610
result.writeTo(writer)
611
}
612
}
613
```