1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 package org.spf4j.io;
33
34 import java.io.Closeable;
35 import java.io.Flushable;
36 import java.io.IOException;
37 import java.io.Writer;
38 import java.nio.CharBuffer;
39
40
41
42
43
44
45 public final class AppendableWriter extends Writer {
46
47 private final Appendable appendable;
48
49 private final boolean flushable;
50
51 private boolean closed;
52
53 public AppendableWriter(final Appendable appendable) {
54 this.appendable = appendable;
55 this.flushable = appendable instanceof Flushable;
56 this.closed = false;
57 }
58
59 @Override
60 public void write(final char[] cbuf, final int off, final int len) throws IOException {
61 checkNotClosed();
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79 appendable.append(CharBuffer.wrap(cbuf), off, off + len);
80 }
81
82 @Override
83 public void write(final int c) throws IOException {
84 checkNotClosed();
85 appendable.append((char) c);
86 }
87
88 @Override
89 public Writer append(final char c) throws IOException {
90 checkNotClosed();
91 appendable.append(c);
92 return this;
93 }
94
95 @Override
96 public Writer append(final CharSequence csq, final int start, final int end) throws IOException {
97 checkNotClosed();
98 appendable.append(csq, start, end);
99 return this;
100 }
101
102 @Override
103 public Writer append(final CharSequence csq) throws IOException {
104 checkNotClosed();
105 appendable.append(csq);
106 return this;
107 }
108
109 @Override
110 public void write(final String str, final int off, final int len) throws IOException {
111 checkNotClosed();
112 appendable.append(str, off, off + len);
113 }
114
115 @Override
116 public void write(final String str) throws IOException {
117 appendable.append(str);
118 }
119
120 @Override
121 public void write(final char[] cbuf) throws IOException {
122 appendable.append(CharBuffer.wrap(cbuf));
123 }
124
125 @Override
126 public void flush() throws IOException {
127 checkNotClosed();
128 if (flushable) {
129 ((Flushable) appendable).flush();
130 }
131 }
132
133 private void checkNotClosed() throws IOException {
134 if (closed) {
135 throw new IOException("Cannot write to closed writer " + this);
136 }
137 }
138
139 @Override
140 public void close() throws IOException {
141 if (!closed) {
142 flush();
143 if (appendable instanceof Closeable) {
144 ((Closeable) appendable).close();
145 }
146 closed = true;
147 }
148 }
149
150 @Override
151 public String toString() {
152 return "AppendableWriter{" + "appendable=" + appendable + ", flushable=" + flushable + ", closed=" + closed + '}';
153 }
154
155 }