1
22
23 package com.liferay.portal.kernel.io.unsync;
24
25 import java.io.IOException;
26 import java.io.Writer;
27
28
37 public class UnsyncBufferedWriter extends Writer {
38
39 public UnsyncBufferedWriter(Writer writer) {
40 this(writer, _DEFAULT_BUFFER_SIZE);
41 }
42
43 public UnsyncBufferedWriter(Writer writer, int size) {
44 if (size <= 0) {
45 throw new IllegalArgumentException("Buffer size is less than 0");
46 }
47
48 this.writer = writer;
49 this.size = size;
50
51 buffer = new char[size];
52 }
53
54 public void close() throws IOException {
55 if (writer == null) {
56 return;
57 }
58
59 if (count > 0) {
60 writer.write(buffer, 0, count);
61
62 count = 0;
63 }
64
65 writer.flush();
66 writer.close();
67
68 writer = null;
69 buffer = null;
70 }
71
72 public void flush() throws IOException {
73 if (writer == null) {
74 throw new IOException("Writer is null");
75 }
76
77 if (count > 0) {
78 writer.write(buffer, 0, count);
79
80 count = 0;
81 }
82
83 writer.flush();
84 }
85
86 public void newLine() throws IOException {
87 write(_LINE_SEPARATOR);
88 }
89
90 public void write(char[] charArray, int offset, int length)
91 throws IOException {
92
93 if (writer == null) {
94 throw new IOException("Writer is null");
95 }
96
97 if (length >= size) {
98 if (count > 0) {
99 writer.write(buffer, 0, count);
100
101 count = 0;
102 }
103
104 writer.write(charArray, offset, length);
105
106 return;
107 }
108
109 if ((count > 0) && (length > (size - count))) {
110 writer.write(buffer, 0, count);
111
112 count = 0;
113 }
114
115 System.arraycopy(charArray, offset, buffer, count, length);
116
117 count += length;
118 }
119
120 public void write(int c) throws IOException {
121 if (writer == null) {
122 throw new IOException("Writer is null");
123 }
124
125 if (count >= size) {
126 writer.write(buffer);
127
128 count = 0;
129 }
130
131 buffer[count++] = (char)c;
132 }
133
134 public void write(String string, int offset, int length)
135 throws IOException {
136
137 if (writer == null) {
138 throw new IOException("Writer is null");
139 }
140
141 int x = offset;
142 int y = offset + length;
143
144 while (x < y) {
145 if (count >= size) {
146 writer.write(buffer);
147
148 count = 0;
149 }
150
151 int leftFreeSpace = size - count;
152 int leftDataSize = y - x;
153
154 if (leftFreeSpace > leftDataSize) {
155 string.getChars(x, y, buffer, count);
156
157 count += leftDataSize;
158
159 break;
160 }
161 else {
162 int copyEnd = x + leftFreeSpace;
163
164 string.getChars(x, copyEnd, buffer, count);
165
166 count += leftFreeSpace;
167
168 x = copyEnd;
169 }
170 }
171 }
172
173 protected char[] buffer;
174 protected int count;
175 protected int size;
176 protected Writer writer;
177
178 private static int _DEFAULT_BUFFER_SIZE = 8192;
179
180 private static String _LINE_SEPARATOR = System.getProperty(
181 "line.separator");
182
183 }