-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHtmlToText.java
337 lines (319 loc) · 9.71 KB
/
HtmlToText.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package FileConvert2Txt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import org.juno.scheduler.util.ConvertException;
/**
* @author denghc
* @desc HTML转格式化的TXT
*/
public class HtmlToText implements IFileToText{
@Override
public String fileToText(byte[] byts, int flag) throws ConvertException {
BufferedReader br = new BufferedReader(new StringReader(new String(byts)));
try {
String HtmlStr = "";
String t = null;
while ((t = br.readLine()) != null) {// 读一行
HtmlStr = HtmlStr + t;
}
br.close();
return html2text(HtmlStr);
} catch (Exception e) {
throw new ConvertException("HTML文件转换格式化文本异常");
} finally {
if(br!=null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String html2text(String html) {
if (html == null || html == "") {
return "";
}
StringBuffer sb = new StringBuffer(html.length());
char[] data = html.toCharArray();
int start = 0;
boolean previousIsPre = false;
Token token = null;
for (;;) {
token = parse(data, start, previousIsPre);
if (token == null)
break;
previousIsPre = token.isPreTag();
sb = sb.append(token.getText());
start += token.getLength();
}
return sb.toString();
}
private Token parse(char[] data, int start, boolean previousIsPre) {
if (start >= data.length)
return null;
// try to read next char:
char c = data[start];
if (c == '<') {
// this is a tag or comment or script:
int end_index = indexOf(data, start + 1, '>');
if (end_index == (-1)) {
// the left is all text!
return new Token(Token.TOKEN_TEXT, data, start, data.length, previousIsPre);
}
String s = new String(data, start, end_index - start + 1);
// now we got s="<...>":
if (s.startsWith("<!--")) { // this is a comment!
int end_comment_index = indexOf(data, start + 1, "-->");
if (end_comment_index == (-1)) {
// illegal end, but treat as comment:
return new Token(Token.TOKEN_COMMENT, data, start, data.length, previousIsPre);
} else
return new Token(Token.TOKEN_COMMENT, data, start, end_comment_index + 3, previousIsPre);
}
String s_lowerCase = s.toLowerCase();
if (s_lowerCase.startsWith("<script")) { // this is a script:
int end_script_index = indexOf(data, start + 1, "</script>");
if (end_script_index == (-1))
// illegal end, but treat as script:
return new Token(Token.TOKEN_SCRIPT, data, start, data.length, previousIsPre);
else
return new Token(Token.TOKEN_SCRIPT, data, start, end_script_index + 9, previousIsPre);
} else { // this is a tag:
return new Token(Token.TOKEN_TAG, data, start, start + s.length(), previousIsPre);
}
}
// this is a text:
int next_tag_index = indexOf(data, start + 1, '<');
if (next_tag_index == (-1))
return new Token(Token.TOKEN_TEXT, data, start, data.length, previousIsPre);
return new Token(Token.TOKEN_TEXT, data, start, next_tag_index, previousIsPre);
}
private int indexOf(char[] data, int start, String s) {
char[] ss = s.toCharArray();
// TODO: performance can improve!
for (int i = start; i < (data.length - ss.length); i++) {
// compare from data[i] with ss[0]:
boolean match = true;
for (int j = 0; j < ss.length; j++) {
if (data[i + j] != ss[j]) {
match = false;
break;
}
}
if (match)
return i;
}
return (-1);
}
private int indexOf(char[] data, int start, char c) {
for (int i = start; i < data.length; i++) {
if (data[i] == c)
return i;
}
return (-1);
}
}
class Token {
public static final int TOKEN_TEXT = 0; // html text.
public static final int TOKEN_COMMENT = 1; // comment like <!-- comments... -->
public static final int TOKEN_TAG = 2; // tag like <pre>, <font>, etc.
public static final int TOKEN_SCRIPT = 3;
private static final char[] TAG_BR = "<br".toCharArray();
private static final char[] TAG_P = "<p".toCharArray();
private static final char[] TAG_LI = "<li".toCharArray();
private static final char[] TAG_PRE = "<pre".toCharArray();
private static final char[] TAG_HR = "<hr".toCharArray();
private static final char[] END_TAG_TD = "</td>".toCharArray();
private static final char[] END_TAG_TR = "</tr>".toCharArray();
private static final char[] END_TAG_LI = "</li>".toCharArray();
private static final Map SPECIAL_CHARS = new HashMap();
private int type;
private String html; // original html
private String text = null; // text!
private int length = 0; // html length
private boolean isPre = false; // isPre tag?
static {
SPECIAL_CHARS.put(""", "\"");
SPECIAL_CHARS.put("<", "<");
SPECIAL_CHARS.put(">", ">");
SPECIAL_CHARS.put("&", "&");
SPECIAL_CHARS.put("®", "(r)");
SPECIAL_CHARS.put("©", "(c)");
SPECIAL_CHARS.put(" ", " ");
SPECIAL_CHARS.put("£", "?");
}
public Token(int type, char[] data, int start, int end, boolean previousIsPre) {
this.type = type;
this.length = end - start;
this.html = new String(data, start, length);
// System.out.println("[Token] html=" + html + ".");
parseText(previousIsPre);
// System.out.println("[Token] text=" + text + ".");
}
public int getLength() {
return length;
}
public boolean isPreTag() {
return isPre;
}
private void parseText(boolean previousIsPre) {
if (type == TOKEN_TAG) {
char[] cs = html.toCharArray();
if (compareTag(TAG_BR, cs) || compareTag(TAG_P, cs))
text = "\n";
else if (compareTag(TAG_LI, cs))
text = "\n* ";
else if (compareTag(TAG_PRE, cs))
isPre = true;
else if (compareTag(TAG_HR, cs))
text = "\n--------\n";
else if (compareString(END_TAG_TD, cs))
text = "\t";
else if (compareString(END_TAG_TR, cs) || compareString(END_TAG_LI, cs))
text = "\n";
}
// text token:
else if (type == TOKEN_TEXT) {
text = toText(html, previousIsPre);
}
}
public String getText() {
return text == null ? "" : text;
}
private String toText(String html, final boolean isPre) {
char[] cs = html.toCharArray();
StringBuffer buffer = new StringBuffer(cs.length);
int start = 0;
boolean continueSpace = false;
char current, next;
for (;;) {
if (start >= cs.length)
break;
current = cs[start]; // read current char
if (start + 1 < cs.length) // and next char
next = cs[start + 1];
else
next = '\0';
if (current == ' ') {
if (isPre || !continueSpace)
buffer = buffer.append(' ');
continueSpace = true;
// continue loop:
start++;
continue;
}
// not ' ', so:
if (current == '\r' && next == '\n') {
if (isPre)
buffer = buffer.append('\n');
// continue loop:
start += 2;
continue;
}
if (current == '\n' || current == '\r') {
if (isPre)
buffer = buffer.append('\n');
// continue loop:
start++;
continue;
}
// cannot continue space:
continueSpace = false;
if (current == '&') {
// maybe special char:
int length = readUtil(cs, start, ';', 10);
if (length == (-1)) { // just '&':
buffer = buffer.append('&');
// continue loop:
start++;
continue;
} else { // check if special character:
String spec = new String(cs, start, length);
String specChar = (String) SPECIAL_CHARS.get(spec);
if (specChar != null) { // special chars!
buffer = buffer.append(specChar);
// continue loop:
start += length;
continue;
} else { // check if like 'Ӓ':
if (next == '#') { // maybe a char
String num = new String(cs, start + 2, length - 3);
try {
int code = Integer.parseInt(num);
if (code > 0 && code < 65536) { // this is a special char:
buffer = buffer.append((char) code);
// continue loop:
start++;
continue;
}
} catch (Exception e) {
}
// just normal char:
buffer = buffer.append("&#");
// continue loop:
start += 2;
continue;
} else { // just '&':
buffer = buffer.append('&');
// continue loop:
start++;
continue;
}
}
}
} else { // just a normal char!
buffer = buffer.append(current);
// continue loop:
start++;
continue;
}
}
return buffer.toString();
}
// read from cs[start] util meet the specified char 'util',
// or null if not found:
private int readUtil(final char[] cs, final int start, final char util, final int maxLength) {
int end = start + maxLength;
if (end > cs.length)
end = cs.length;
for (int i = start; i < start + maxLength; i++) {
if (cs[i] == util) {
return i - start + 1;
}
}
return (-1);
}
// compare standard tag "<input" with tag "<INPUT value=aa>"
private boolean compareTag(final char[] ori_tag, char[] tag) {
if (ori_tag.length >= tag.length)
return false;
for (int i = 0; i < ori_tag.length; i++) {
if (Character.toLowerCase(tag[i]) != ori_tag[i])
return false;
}
// the following char should not be a-z:
if (tag.length > ori_tag.length) {
char c = Character.toLowerCase(tag[ori_tag.length]);
if (c < 'a' || c > 'z')
return true;
return false;
}
return true;
}
private boolean compareString(final char[] ori, char[] comp) {
if (ori.length > comp.length)
return false;
for (int i = 0; i < ori.length; i++) {
if (Character.toLowerCase(comp[i]) != ori[i])
return false;
}
return true;
}
public String toString() {
return html;
}
}