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