This is the second post about my experiments with a fluent I/O API. This post covers how to extend the API.
Doctoring streams
Let's look at some of the API's Doctor
implementations. The code uses some static imports to keep things clean:
import static demo.fluentio.Closers.closer; |
This code writes UTF-8 character data, prefixing the stream with a Unicode byte-order-mark:
private void save(File output, String data) throws IOException {
|
This code detects the encoding of a text file by inspecting the byte-order-mark:
private String load(File input) throws IOException {
|
Extending the API
You can add support for other stream types by implementing your
own Doctor
implementations. This Doctor
decorates a stream with a filter class (elided) that turns characters
into upper case:
public class ShoutyDoctor implements |
This code prints out WOULD YOU LIKE TO PLAY A GAME?
:
PrintWriter shouter = IO.out(SHUT, System.out) |
Doctoring streams
Adding decorators isn't the only thing you can do with a Doctor
implementation. This code creates one to perform a byte copy operation:
private static void copy(File src, File dest) throws IOException {
|
Related posts
- Part 1: introduction
- Part 2: extending the API
- Part 3: error handling
- Part 4: conclusions and downloads
Comments & criticism are welcome.
No comments:
Post a Comment
All comments are moderated