1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.doxia.util;
20
21 import java.io.BufferedWriter;
22 import java.io.IOException;
23 import java.io.Writer;
24
25
26
27
28 public class LineBreaker {
29
30 public static final int DEFAULT_MAX_LINE_LENGTH = 78;
31
32
33 private static final String EOL = System.getProperty("line.separator");
34
35
36 private Writer destination;
37
38
39 private BufferedWriter writer;
40
41
42 private int maxLineLength;
43
44
45 private int lineLength = 0;
46
47
48 private StringBuilder word = new StringBuilder(1024);
49
50
51
52
53
54
55 public LineBreaker(Writer out) {
56 this(out, DEFAULT_MAX_LINE_LENGTH);
57 }
58
59
60
61
62
63
64
65 public LineBreaker(Writer out, int max) {
66 if (max <= 0) {
67 throw new IllegalArgumentException("max must be a positive integer");
68 }
69
70 destination = out;
71 this.maxLineLength = max;
72 writer = new BufferedWriter(out);
73 }
74
75
76
77
78
79
80 public Writer getDestination() {
81 return destination;
82 }
83
84
85
86
87
88
89
90 public void write(String text) throws IOException {
91 write(text, false);
92 }
93
94
95
96
97
98
99
100 public void write(String text, boolean preserveSpace) {
101 int length = text.length();
102
103 try {
104 for (int i = 0; i < length; ++i) {
105 char c = text.charAt(i);
106
107 switch (c) {
108 case ' ':
109 if (preserveSpace) {
110 word.append(c);
111 } else {
112 writeWord();
113 }
114 break;
115
116 case '\r':
117
118 if (i + 1 < length && text.charAt(i + 1) == '\n') {
119 break;
120 }
121
122 case '\n':
123 writeWord();
124 writer.write(EOL);
125 lineLength = 0;
126 break;
127
128 default:
129 word.append(c);
130 }
131 }
132 } catch (Exception e) {
133
134 }
135 }
136
137
138
139
140
141 public void flush() {
142 try {
143 writeWord();
144 writer.flush();
145 } catch (IOException e) {
146
147 }
148 }
149
150
151
152
153
154
155 private void writeWord() throws IOException {
156 int length = word.length();
157 if (length > 0) {
158 if (lineLength > 0) {
159 if (lineLength + 1 + length > maxLineLength) {
160 writer.write(EOL);
161 lineLength = 0;
162 } else {
163 writer.write(' ');
164 ++lineLength;
165 }
166 }
167
168 writer.write(word.toString());
169 word.setLength(0);
170
171 lineLength += length;
172 }
173 }
174
175
176
177
178 public void close() {
179 if (writer == null) {
180 return;
181 }
182
183 try {
184 writer.close();
185 } catch (IOException ex) {
186
187 }
188 }
189 }