1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.yaml.snakeyaml.reader;
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.InputStreamReader;
44 import java.io.PushbackInputStream;
45 import java.io.Reader;
46
47
48
49
50
51 public class UnicodeReader extends Reader {
52 PushbackInputStream internalIn;
53 InputStreamReader internalIn2 = null;
54
55 private static final int BOM_SIZE = 3;
56
57
58
59
60
61 public UnicodeReader(InputStream in) {
62 internalIn = new PushbackInputStream(in, BOM_SIZE);
63 }
64
65
66
67
68
69 public String getEncoding() {
70 return internalIn2.getEncoding();
71 }
72
73
74
75
76
77 protected void init() throws IOException {
78 if (internalIn2 != null)
79 return;
80
81 String encoding;
82 byte bom[] = new byte[BOM_SIZE];
83 int n, unread;
84 n = internalIn.read(bom, 0, bom.length);
85
86 if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) {
87 encoding = "UTF-8";
88 unread = n - 3;
89 } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
90 encoding = "UTF-16BE";
91 unread = n - 2;
92 } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
93 encoding = "UTF-16LE";
94 unread = n - 2;
95 } else {
96
97 encoding = "UTF-8";
98 unread = n;
99 }
100
101 if (unread > 0)
102 internalIn.unread(bom, (n - unread), unread);
103
104
105 internalIn2 = new InputStreamReader(internalIn, encoding);
106 }
107
108 public void close() throws IOException {
109 init();
110 internalIn2.close();
111 }
112
113 public int read(char[] cbuf, int off, int len) throws IOException {
114 init();
115 return internalIn2.read(cbuf, off, len);
116 }
117 }