~ubuntu-branches/ubuntu/lucid/groovy/lucid

« back to all changes in this revision

Viewing changes to src/main/groovy/util/CharsetToolkit.java

  • Committer: Bazaar Package Importer
  • Author(s): Varun Hiremath, Torsten Werner, Varun Hiremath
  • Date: 2009-04-01 19:24:19 UTC
  • mfrom: (3.2.2 squeeze)
  • Revision ID: james.westby@ubuntu.com-20090401192419-c5mpylqhcdkv3zuv
Tags: 1.6.0-1
[ Torsten Werner ]
* New upstream release (Closes: #521648)
* Remove Build-Depends: libclassworlds-java.
* Switch to source and target version 1.5.

[ Varun Hiremath ]
* Fix build.xml file
* Add ivy to Build-Depends
* Remove unnecessary Depends -- collections3, mx4j and xpp3 
* Add build.diff patch to fix a build error
* Use quilt to manage patches
* Update manpage (Closes: #507862)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 * Copyright 2003-2007 the original author or authors.
3
 
 *
4
 
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 
 * you may not use this file except in compliance with the License.
6
 
 * You may obtain a copy of the License at
7
 
 *
8
 
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 
 *
10
 
 * Unless required by applicable law or agreed to in writing, software
11
 
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 
 * See the License for the specific language governing permissions and
14
 
 * limitations under the License.
15
 
 */
16
 
 
17
 
package groovy.util;
18
 
 
19
 
import java.io.*;
20
 
import java.nio.charset.Charset;
21
 
import java.util.Collection;
22
 
 
23
 
/**
24
 
 * <p>Utility class to guess the encoding of a given text file.</p>
25
 
 *
26
 
 * <p>Unicode files encoded in UTF-16 (low or big endian) or UTF-8 files
27
 
 * with a Byte Order Marker are correctly discovered. For UTF-8 files with no BOM, if the buffer
28
 
 * is wide enough, the charset should also be discovered.</p>
29
 
 *
30
 
 * <p>A byte buffer of 4KB is usually sufficient to be able to guess the encoding.</p>
31
 
 *
32
 
 * <p>Usage:</p>
33
 
 * <pre>
34
 
 * // guess the encoding
35
 
 * Charset guessedCharset = CharsetToolkit.guessEncoding(file, 4096);
36
 
 *
37
 
 * // create a reader with the correct charset
38
 
 * CharsetToolkit toolkit = new CharsetToolkit(file);
39
 
 * BufferedReader reader = toolkit.getReader();
40
 
 *
41
 
 * // read the file content
42
 
 * String line;
43
 
 * while ((line = br.readLine())!= null)
44
 
 * {
45
 
 *     System.out.println(line);
46
 
 * }
47
 
 * </pre>
48
 
 *
49
 
 * @author Guillaume Laforge
50
 
 */
51
 
public class CharsetToolkit {
52
 
    private byte[] buffer;
53
 
    private Charset defaultCharset;
54
 
    private Charset charset;
55
 
    private boolean enforce8Bit = true;
56
 
    private final File file;
57
 
    private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
58
 
 
59
 
    /**
60
 
     * Constructor of the <code>CharsetToolkit</code> utility class.
61
 
     *
62
 
     * @param file of which we want to know the encoding.
63
 
     */
64
 
    public CharsetToolkit(File file) throws IOException {
65
 
        this.file = file;
66
 
        this.defaultCharset = getDefaultSystemCharset();
67
 
        this.charset = null;
68
 
        InputStream input = new FileInputStream(file);
69
 
        try {
70
 
            byte[] bytes = new byte[4096];
71
 
            int bytesRead = input.read(bytes);
72
 
            if (bytesRead == -1) {
73
 
                this.buffer = EMPTY_BYTE_ARRAY;
74
 
            }
75
 
            else if (bytesRead < 4096) {
76
 
                byte[] bytesToGuess = new byte[bytesRead];
77
 
                System.arraycopy(bytes, 0, bytesToGuess, 0, bytesRead);
78
 
                this.buffer = bytesToGuess;
79
 
            }
80
 
            else {
81
 
                this.buffer = bytes;
82
 
            }
83
 
        } finally {
84
 
            try {input.close();} catch (IOException e){
85
 
                // IGNORE
86
 
            }
87
 
        }
88
 
    }
89
 
 
90
 
    /**
91
 
     * Defines the default <code>Charset</code> used in case the buffer represents
92
 
     * an 8-bit <code>Charset</code>.
93
 
     *
94
 
     * @param defaultCharset the default <code>Charset</code> to be returned by <code>guessEncoding()</code>
95
 
     * if an 8-bit <code>Charset</code> is encountered.
96
 
     */
97
 
    public void setDefaultCharset(Charset defaultCharset) {
98
 
        if (defaultCharset != null)
99
 
            this.defaultCharset = defaultCharset;
100
 
        else
101
 
            this.defaultCharset = getDefaultSystemCharset();
102
 
    }
103
 
 
104
 
    public Charset getCharset() {
105
 
        if (this.charset == null)
106
 
            this.charset = guessEncoding();
107
 
        return charset;
108
 
    }
109
 
 
110
 
    /**
111
 
     * If US-ASCII is recognized, enforce to return the default encoding, rather than US-ASCII.
112
 
     * It might be a file without any special character in the range 128-255, but that may be or become
113
 
     * a file encoded with the default <code>charset</code> rather than US-ASCII.
114
 
     *
115
 
     * @param enforce a boolean specifying the use or not of US-ASCII.
116
 
     */
117
 
    public void setEnforce8Bit(boolean enforce) {
118
 
        this.enforce8Bit = enforce;
119
 
    }
120
 
 
121
 
    /**
122
 
     * Gets the enforce8Bit flag, in case we do not want to ever get a US-ASCII encoding.
123
 
     *
124
 
     * @return a boolean representing the flag of use of US-ASCII.
125
 
     */
126
 
    public boolean getEnforce8Bit() {
127
 
        return this.enforce8Bit;
128
 
    }
129
 
 
130
 
    /**
131
 
     * Retrieves the default Charset
132
 
     */
133
 
    public Charset getDefaultCharset() {
134
 
        return defaultCharset;
135
 
    }
136
 
 
137
 
    /**
138
 
     * <p>Guess the encoding of the provided buffer.</p>
139
 
     * If Byte Order Markers are encountered at the beginning of the buffer, we immidiately
140
 
     * return the charset implied by this BOM. Otherwise, the file would not be a human
141
 
     * readable text file.</p>
142
 
     *
143
 
     * <p>If there is no BOM, this method tries to discern whether the file is UTF-8 or not.
144
 
     * If it is not UTF-8, we assume the encoding is the default system encoding
145
 
     * (of course, it might be any 8-bit charset, but usually, an 8-bit charset is the default one).</p>
146
 
     *
147
 
     * <p>It is possible to discern UTF-8 thanks to the pattern of characters with a multi-byte sequence.</p>
148
 
     * <pre>
149
 
     * UCS-4 range (hex.)        UTF-8 octet sequence (binary)
150
 
     * 0000 0000-0000 007F       0xxxxxxx
151
 
     * 0000 0080-0000 07FF       110xxxxx 10xxxxxx
152
 
     * 0000 0800-0000 FFFF       1110xxxx 10xxxxxx 10xxxxxx
153
 
     * 0001 0000-001F FFFF       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
154
 
     * 0020 0000-03FF FFFF       111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
155
 
     * 0400 0000-7FFF FFFF       1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
156
 
     * </pre>
157
 
     * <p>With UTF-8, 0xFE and 0xFF never appear.</p>
158
 
     *
159
 
     * @return the Charset recognized.
160
 
     */
161
 
    private Charset guessEncoding() {
162
 
        // if the file has a Byte Order Marker, we can assume the file is in UTF-xx
163
 
        // otherwise, the file would not be human readable
164
 
        if (hasUTF8Bom())
165
 
            return Charset.forName("UTF-8");
166
 
        if (hasUTF16LEBom())
167
 
            return Charset.forName("UTF-16LE");
168
 
        if (hasUTF16BEBom())
169
 
            return Charset.forName("UTF-16BE");
170
 
 
171
 
        // if a byte has its most significant bit set, the file is in UTF-8 or in the default encoding
172
 
        // otherwise, the file is in US-ASCII
173
 
        boolean highOrderBit = false;
174
 
 
175
 
        // if the file is in UTF-8, high order bytes must have a certain value, in order to be valid
176
 
        // if it's not the case, we can assume the encoding is the default encoding of the system
177
 
        boolean validU8Char = true;
178
 
 
179
 
        // TODO the buffer is not read up to the end, but up to length - 6
180
 
 
181
 
        int length = buffer.length;
182
 
        int i = 0;
183
 
        while (i < length - 6) {
184
 
            byte b0 = buffer[i];
185
 
            byte b1 = buffer[i + 1];
186
 
            byte b2 = buffer[i + 2];
187
 
            byte b3 = buffer[i + 3];
188
 
            byte b4 = buffer[i + 4];
189
 
            byte b5 = buffer[i + 5];
190
 
            if (b0 < 0) {
191
 
                // a high order bit was encountered, thus the encoding is not US-ASCII
192
 
                // it may be either an 8-bit encoding or UTF-8
193
 
                highOrderBit = true;
194
 
                // a two-bytes sequence was encoutered
195
 
                if (isTwoBytesSequence(b0)) {
196
 
                    // there must be one continuation byte of the form 10xxxxxx,
197
 
                    // otherwise the following characteris is not a valid UTF-8 construct
198
 
                    if (!isContinuationChar(b1))
199
 
                        validU8Char = false;
200
 
                    else
201
 
                        i++;
202
 
                }
203
 
                // a three-bytes sequence was encoutered
204
 
                else if (isThreeBytesSequence(b0)) {
205
 
                    // there must be two continuation bytes of the form 10xxxxxx,
206
 
                    // otherwise the following characteris is not a valid UTF-8 construct
207
 
                    if (!(isContinuationChar(b1) && isContinuationChar(b2)))
208
 
                        validU8Char = false;
209
 
                    else
210
 
                        i += 2;
211
 
                }
212
 
                // a four-bytes sequence was encoutered
213
 
                else if (isFourBytesSequence(b0)) {
214
 
                    // there must be three continuation bytes of the form 10xxxxxx,
215
 
                    // otherwise the following characteris is not a valid UTF-8 construct
216
 
                    if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3)))
217
 
                        validU8Char = false;
218
 
                    else
219
 
                        i += 3;
220
 
                }
221
 
                // a five-bytes sequence was encoutered
222
 
                else if (isFiveBytesSequence(b0)) {
223
 
                    // there must be four continuation bytes of the form 10xxxxxx,
224
 
                    // otherwise the following characteris is not a valid UTF-8 construct
225
 
                    if (!(isContinuationChar(b1)
226
 
                        && isContinuationChar(b2)
227
 
                        && isContinuationChar(b3)
228
 
                        && isContinuationChar(b4)))
229
 
                        validU8Char = false;
230
 
                    else
231
 
                        i += 4;
232
 
                }
233
 
                // a six-bytes sequence was encoutered
234
 
                else if (isSixBytesSequence(b0)) {
235
 
                    // there must be five continuation bytes of the form 10xxxxxx,
236
 
                    // otherwise the following characteris is not a valid UTF-8 construct
237
 
                    if (!(isContinuationChar(b1)
238
 
                        && isContinuationChar(b2)
239
 
                        && isContinuationChar(b3)
240
 
                        && isContinuationChar(b4)
241
 
                        && isContinuationChar(b5)))
242
 
                        validU8Char = false;
243
 
                    else
244
 
                        i += 5;
245
 
                }
246
 
                else
247
 
                    validU8Char = false;
248
 
            }
249
 
            if (!validU8Char)
250
 
                break;
251
 
            i++;
252
 
        }
253
 
        // if no byte with an high order bit set, the encoding is US-ASCII
254
 
        // (it might have been UTF-7, but this encoding is usually internally used only by mail systems)
255
 
        if (!highOrderBit) {
256
 
            // returns the default charset rather than US-ASCII if the enforce8Bit flag is set.
257
 
            if (this.enforce8Bit)
258
 
                return this.defaultCharset;
259
 
            else
260
 
                return Charset.forName("US-ASCII");
261
 
        }
262
 
        // if no invalid UTF-8 were encountered, we can assume the encoding is UTF-8,
263
 
        // otherwise the file would not be human readable
264
 
        if (validU8Char)
265
 
            return Charset.forName("UTF-8");
266
 
        // finally, if it's not UTF-8 nor US-ASCII, let's assume the encoding is the default encoding
267
 
        return this.defaultCharset;
268
 
    }
269
 
 
270
 
    /**
271
 
     * If the byte has the form 10xxxxx, then it's a continuation byte of a multiple byte character;
272
 
     *
273
 
     * @param b a byte.
274
 
     * @return true if it's a continuation char.
275
 
     */
276
 
    private static boolean isContinuationChar(byte b) {
277
 
        return -128 <= b && b <= -65;
278
 
    }
279
 
 
280
 
    /**
281
 
     * If the byte has the form 110xxxx, then it's the first byte of a two-bytes sequence character.
282
 
     *
283
 
     * @param b a byte.
284
 
     * @return true if it's the first byte of a two-bytes sequence.
285
 
     */
286
 
    private static boolean isTwoBytesSequence(byte b) {
287
 
        return -64 <= b && b <= -33;
288
 
    }
289
 
 
290
 
    /**
291
 
     * If the byte has the form 1110xxx, then it's the first byte of a three-bytes sequence character.
292
 
     *
293
 
     * @param b a byte.
294
 
     * @return true if it's the first byte of a three-bytes sequence.
295
 
     */
296
 
    private static boolean isThreeBytesSequence(byte b) {
297
 
        return -32 <= b && b <= -17;
298
 
    }
299
 
 
300
 
    /**
301
 
     * If the byte has the form 11110xx, then it's the first byte of a four-bytes sequence character.
302
 
     *
303
 
     * @param b a byte.
304
 
     * @return true if it's the first byte of a four-bytes sequence.
305
 
     */
306
 
    private static boolean isFourBytesSequence(byte b) {
307
 
        return -16 <= b && b <= -9;
308
 
    }
309
 
 
310
 
    /**
311
 
     * If the byte has the form 11110xx, then it's the first byte of a five-bytes sequence character.
312
 
     *
313
 
     * @param b a byte.
314
 
     * @return true if it's the first byte of a five-bytes sequence.
315
 
     */
316
 
    private static boolean isFiveBytesSequence(byte b) {
317
 
        return -8 <= b && b <= -5;
318
 
    }
319
 
 
320
 
    /**
321
 
     * If the byte has the form 1110xxx, then it's the first byte of a six-bytes sequence character.
322
 
     *
323
 
     * @param b a byte.
324
 
     * @return true if it's the first byte of a six-bytes sequence.
325
 
     */
326
 
    private static boolean isSixBytesSequence(byte b) {
327
 
        return -4 <= b && b <= -3;
328
 
    }
329
 
 
330
 
    /**
331
 
     * Retrieve the default charset of the system.
332
 
     *
333
 
     * @return the default <code>Charset</code>.
334
 
     */
335
 
    public static Charset getDefaultSystemCharset() {
336
 
        return Charset.forName(System.getProperty("file.encoding"));
337
 
    }
338
 
 
339
 
    /**
340
 
     * Has a Byte Order Marker for UTF-8 (Used by Microsoft's Notepad and other editors).
341
 
     *
342
 
     * @return true if the buffer has a BOM for UTF8.
343
 
     */
344
 
    public boolean hasUTF8Bom() {
345
 
        if (buffer.length >= 3)
346
 
            return (buffer[0] == -17 && buffer[1] == -69 && buffer[2] == -65);
347
 
        else
348
 
            return false;
349
 
    }
350
 
 
351
 
    /**
352
 
     * Has a Byte Order Marker for UTF-16 Low Endian
353
 
     * (ucs-2le, ucs-4le, and ucs-16le).
354
 
     *
355
 
     * @return true if the buffer has a BOM for UTF-16 Low Endian.
356
 
     */
357
 
    public boolean hasUTF16LEBom() {
358
 
        if (buffer.length >= 2)
359
 
            return (buffer[0] == -1 && buffer[1] == -2);
360
 
        else
361
 
            return false;
362
 
    }
363
 
 
364
 
    /**
365
 
     * Has a Byte Order Marker for UTF-16 Big Endian
366
 
     * (utf-16 and ucs-2).
367
 
     *
368
 
     * @return true if the buffer has a BOM for UTF-16 Big Endian.
369
 
     */
370
 
    public boolean hasUTF16BEBom() {
371
 
        if (buffer.length >= 2)
372
 
            return (buffer[0] == -2 && buffer[1] == -1);
373
 
        else
374
 
            return false;
375
 
    }
376
 
 
377
 
    /**
378
 
     * Gets a <code>BufferedReader</code> (indeed a <code>LineNumberReader</code>) from the <code>File</code>
379
 
     * specified in the constructor of <code>CharsetToolkit</code> using the charset discovered by the
380
 
     * method <code>guessEncoding()</code>.
381
 
     *
382
 
     * @return a <code>BufferedReader</code>
383
 
     * @throws FileNotFoundException if the file is not found.
384
 
     */
385
 
    public BufferedReader getReader() throws FileNotFoundException {
386
 
        LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), getCharset()));
387
 
        if (hasUTF8Bom() || hasUTF16LEBom() || hasUTF16BEBom()) {
388
 
            try {
389
 
                reader.read();
390
 
            }
391
 
            catch (IOException e) {
392
 
                // should never happen, as a file with no content
393
 
                // but with a BOM has at least one char
394
 
            }
395
 
        }
396
 
        return reader;
397
 
    }
398
 
 
399
 
    /**
400
 
     * Retrieves all the available <code>Charset</code>s on the platform,
401
 
     * among which the default <code>charset</code>.
402
 
     *
403
 
     * @return an array of <code>Charset</code>s.
404
 
     */
405
 
    public static Charset[] getAvailableCharsets() {
406
 
        Collection collection = Charset.availableCharsets().values();
407
 
        return (Charset[]) collection.toArray(new Charset[collection.size()]);
408
 
    }
409
 
}
 
1
/*
 
2
 * Copyright 2003-2007 the original author or authors.
 
3
 *
 
4
 * Licensed under the Apache License, Version 2.0 (the "License");
 
5
 * you may not use this file except in compliance with the License.
 
6
 * You may obtain a copy of the License at
 
7
 *
 
8
 *     http://www.apache.org/licenses/LICENSE-2.0
 
9
 *
 
10
 * Unless required by applicable law or agreed to in writing, software
 
11
 * distributed under the License is distributed on an "AS IS" BASIS,
 
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
13
 * See the License for the specific language governing permissions and
 
14
 * limitations under the License.
 
15
 */
 
16
 
 
17
package groovy.util;
 
18
 
 
19
import java.io.*;
 
20
import java.nio.charset.Charset;
 
21
import java.util.Collection;
 
22
 
 
23
/**
 
24
 * <p>Utility class to guess the encoding of a given text file.</p>
 
25
 *
 
26
 * <p>Unicode files encoded in UTF-16 (low or big endian) or UTF-8 files
 
27
 * with a Byte Order Marker are correctly discovered. For UTF-8 files with no BOM, if the buffer
 
28
 * is wide enough, the charset should also be discovered.</p>
 
29
 *
 
30
 * <p>A byte buffer of 4KB is usually sufficient to be able to guess the encoding.</p>
 
31
 *
 
32
 * <p>Usage:</p>
 
33
 * <pre>
 
34
 * // guess the encoding
 
35
 * Charset guessedCharset = CharsetToolkit.guessEncoding(file, 4096);
 
36
 *
 
37
 * // create a reader with the correct charset
 
38
 * CharsetToolkit toolkit = new CharsetToolkit(file);
 
39
 * BufferedReader reader = toolkit.getReader();
 
40
 *
 
41
 * // read the file content
 
42
 * String line;
 
43
 * while ((line = br.readLine())!= null)
 
44
 * {
 
45
 *     System.out.println(line);
 
46
 * }
 
47
 * </pre>
 
48
 *
 
49
 * @author Guillaume Laforge
 
50
 */
 
51
public class CharsetToolkit {
 
52
    private byte[] buffer;
 
53
    private Charset defaultCharset;
 
54
    private Charset charset;
 
55
    private boolean enforce8Bit = true;
 
56
    private final File file;
 
57
    private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
 
58
 
 
59
    /**
 
60
     * Constructor of the <code>CharsetToolkit</code> utility class.
 
61
     *
 
62
     * @param file of which we want to know the encoding.
 
63
     */
 
64
    public CharsetToolkit(File file) throws IOException {
 
65
        this.file = file;
 
66
        this.defaultCharset = getDefaultSystemCharset();
 
67
        this.charset = null;
 
68
        InputStream input = new FileInputStream(file);
 
69
        try {
 
70
            byte[] bytes = new byte[4096];
 
71
            int bytesRead = input.read(bytes);
 
72
            if (bytesRead == -1) {
 
73
                this.buffer = EMPTY_BYTE_ARRAY;
 
74
            }
 
75
            else if (bytesRead < 4096) {
 
76
                byte[] bytesToGuess = new byte[bytesRead];
 
77
                System.arraycopy(bytes, 0, bytesToGuess, 0, bytesRead);
 
78
                this.buffer = bytesToGuess;
 
79
            }
 
80
            else {
 
81
                this.buffer = bytes;
 
82
            }
 
83
        } finally {
 
84
            try {input.close();} catch (IOException e){
 
85
                // IGNORE
 
86
            }
 
87
        }
 
88
    }
 
89
 
 
90
    /**
 
91
     * Defines the default <code>Charset</code> used in case the buffer represents
 
92
     * an 8-bit <code>Charset</code>.
 
93
     *
 
94
     * @param defaultCharset the default <code>Charset</code> to be returned by <code>guessEncoding()</code>
 
95
     * if an 8-bit <code>Charset</code> is encountered.
 
96
     */
 
97
    public void setDefaultCharset(Charset defaultCharset) {
 
98
        if (defaultCharset != null)
 
99
            this.defaultCharset = defaultCharset;
 
100
        else
 
101
            this.defaultCharset = getDefaultSystemCharset();
 
102
    }
 
103
 
 
104
    public Charset getCharset() {
 
105
        if (this.charset == null)
 
106
            this.charset = guessEncoding();
 
107
        return charset;
 
108
    }
 
109
 
 
110
    /**
 
111
     * If US-ASCII is recognized, enforce to return the default encoding, rather than US-ASCII.
 
112
     * It might be a file without any special character in the range 128-255, but that may be or become
 
113
     * a file encoded with the default <code>charset</code> rather than US-ASCII.
 
114
     *
 
115
     * @param enforce a boolean specifying the use or not of US-ASCII.
 
116
     */
 
117
    public void setEnforce8Bit(boolean enforce) {
 
118
        this.enforce8Bit = enforce;
 
119
    }
 
120
 
 
121
    /**
 
122
     * Gets the enforce8Bit flag, in case we do not want to ever get a US-ASCII encoding.
 
123
     *
 
124
     * @return a boolean representing the flag of use of US-ASCII.
 
125
     */
 
126
    public boolean getEnforce8Bit() {
 
127
        return this.enforce8Bit;
 
128
    }
 
129
 
 
130
    /**
 
131
     * Retrieves the default Charset
 
132
     */
 
133
    public Charset getDefaultCharset() {
 
134
        return defaultCharset;
 
135
    }
 
136
 
 
137
    /**
 
138
     * <p>Guess the encoding of the provided buffer.</p>
 
139
     * If Byte Order Markers are encountered at the beginning of the buffer, we immidiately
 
140
     * return the charset implied by this BOM. Otherwise, the file would not be a human
 
141
     * readable text file.</p>
 
142
     *
 
143
     * <p>If there is no BOM, this method tries to discern whether the file is UTF-8 or not.
 
144
     * If it is not UTF-8, we assume the encoding is the default system encoding
 
145
     * (of course, it might be any 8-bit charset, but usually, an 8-bit charset is the default one).</p>
 
146
     *
 
147
     * <p>It is possible to discern UTF-8 thanks to the pattern of characters with a multi-byte sequence.</p>
 
148
     * <pre>
 
149
     * UCS-4 range (hex.)        UTF-8 octet sequence (binary)
 
150
     * 0000 0000-0000 007F       0xxxxxxx
 
151
     * 0000 0080-0000 07FF       110xxxxx 10xxxxxx
 
152
     * 0000 0800-0000 FFFF       1110xxxx 10xxxxxx 10xxxxxx
 
153
     * 0001 0000-001F FFFF       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
 
154
     * 0020 0000-03FF FFFF       111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
 
155
     * 0400 0000-7FFF FFFF       1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
 
156
     * </pre>
 
157
     * <p>With UTF-8, 0xFE and 0xFF never appear.</p>
 
158
     *
 
159
     * @return the Charset recognized.
 
160
     */
 
161
    private Charset guessEncoding() {
 
162
        // if the file has a Byte Order Marker, we can assume the file is in UTF-xx
 
163
        // otherwise, the file would not be human readable
 
164
        if (hasUTF8Bom())
 
165
            return Charset.forName("UTF-8");
 
166
        if (hasUTF16LEBom())
 
167
            return Charset.forName("UTF-16LE");
 
168
        if (hasUTF16BEBom())
 
169
            return Charset.forName("UTF-16BE");
 
170
 
 
171
        // if a byte has its most significant bit set, the file is in UTF-8 or in the default encoding
 
172
        // otherwise, the file is in US-ASCII
 
173
        boolean highOrderBit = false;
 
174
 
 
175
        // if the file is in UTF-8, high order bytes must have a certain value, in order to be valid
 
176
        // if it's not the case, we can assume the encoding is the default encoding of the system
 
177
        boolean validU8Char = true;
 
178
 
 
179
        // TODO the buffer is not read up to the end, but up to length - 6
 
180
 
 
181
        int length = buffer.length;
 
182
        int i = 0;
 
183
        while (i < length - 6) {
 
184
            byte b0 = buffer[i];
 
185
            byte b1 = buffer[i + 1];
 
186
            byte b2 = buffer[i + 2];
 
187
            byte b3 = buffer[i + 3];
 
188
            byte b4 = buffer[i + 4];
 
189
            byte b5 = buffer[i + 5];
 
190
            if (b0 < 0) {
 
191
                // a high order bit was encountered, thus the encoding is not US-ASCII
 
192
                // it may be either an 8-bit encoding or UTF-8
 
193
                highOrderBit = true;
 
194
                // a two-bytes sequence was encoutered
 
195
                if (isTwoBytesSequence(b0)) {
 
196
                    // there must be one continuation byte of the form 10xxxxxx,
 
197
                    // otherwise the following characteris is not a valid UTF-8 construct
 
198
                    if (!isContinuationChar(b1))
 
199
                        validU8Char = false;
 
200
                    else
 
201
                        i++;
 
202
                }
 
203
                // a three-bytes sequence was encoutered
 
204
                else if (isThreeBytesSequence(b0)) {
 
205
                    // there must be two continuation bytes of the form 10xxxxxx,
 
206
                    // otherwise the following characteris is not a valid UTF-8 construct
 
207
                    if (!(isContinuationChar(b1) && isContinuationChar(b2)))
 
208
                        validU8Char = false;
 
209
                    else
 
210
                        i += 2;
 
211
                }
 
212
                // a four-bytes sequence was encoutered
 
213
                else if (isFourBytesSequence(b0)) {
 
214
                    // there must be three continuation bytes of the form 10xxxxxx,
 
215
                    // otherwise the following characteris is not a valid UTF-8 construct
 
216
                    if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3)))
 
217
                        validU8Char = false;
 
218
                    else
 
219
                        i += 3;
 
220
                }
 
221
                // a five-bytes sequence was encoutered
 
222
                else if (isFiveBytesSequence(b0)) {
 
223
                    // there must be four continuation bytes of the form 10xxxxxx,
 
224
                    // otherwise the following characteris is not a valid UTF-8 construct
 
225
                    if (!(isContinuationChar(b1)
 
226
                        && isContinuationChar(b2)
 
227
                        && isContinuationChar(b3)
 
228
                        && isContinuationChar(b4)))
 
229
                        validU8Char = false;
 
230
                    else
 
231
                        i += 4;
 
232
                }
 
233
                // a six-bytes sequence was encoutered
 
234
                else if (isSixBytesSequence(b0)) {
 
235
                    // there must be five continuation bytes of the form 10xxxxxx,
 
236
                    // otherwise the following characteris is not a valid UTF-8 construct
 
237
                    if (!(isContinuationChar(b1)
 
238
                        && isContinuationChar(b2)
 
239
                        && isContinuationChar(b3)
 
240
                        && isContinuationChar(b4)
 
241
                        && isContinuationChar(b5)))
 
242
                        validU8Char = false;
 
243
                    else
 
244
                        i += 5;
 
245
                }
 
246
                else
 
247
                    validU8Char = false;
 
248
            }
 
249
            if (!validU8Char)
 
250
                break;
 
251
            i++;
 
252
        }
 
253
        // if no byte with an high order bit set, the encoding is US-ASCII
 
254
        // (it might have been UTF-7, but this encoding is usually internally used only by mail systems)
 
255
        if (!highOrderBit) {
 
256
            // returns the default charset rather than US-ASCII if the enforce8Bit flag is set.
 
257
            if (this.enforce8Bit)
 
258
                return this.defaultCharset;
 
259
            else
 
260
                return Charset.forName("US-ASCII");
 
261
        }
 
262
        // if no invalid UTF-8 were encountered, we can assume the encoding is UTF-8,
 
263
        // otherwise the file would not be human readable
 
264
        if (validU8Char)
 
265
            return Charset.forName("UTF-8");
 
266
        // finally, if it's not UTF-8 nor US-ASCII, let's assume the encoding is the default encoding
 
267
        return this.defaultCharset;
 
268
    }
 
269
 
 
270
    /**
 
271
     * If the byte has the form 10xxxxx, then it's a continuation byte of a multiple byte character;
 
272
     *
 
273
     * @param b a byte.
 
274
     * @return true if it's a continuation char.
 
275
     */
 
276
    private static boolean isContinuationChar(byte b) {
 
277
        return -128 <= b && b <= -65;
 
278
    }
 
279
 
 
280
    /**
 
281
     * If the byte has the form 110xxxx, then it's the first byte of a two-bytes sequence character.
 
282
     *
 
283
     * @param b a byte.
 
284
     * @return true if it's the first byte of a two-bytes sequence.
 
285
     */
 
286
    private static boolean isTwoBytesSequence(byte b) {
 
287
        return -64 <= b && b <= -33;
 
288
    }
 
289
 
 
290
    /**
 
291
     * If the byte has the form 1110xxx, then it's the first byte of a three-bytes sequence character.
 
292
     *
 
293
     * @param b a byte.
 
294
     * @return true if it's the first byte of a three-bytes sequence.
 
295
     */
 
296
    private static boolean isThreeBytesSequence(byte b) {
 
297
        return -32 <= b && b <= -17;
 
298
    }
 
299
 
 
300
    /**
 
301
     * If the byte has the form 11110xx, then it's the first byte of a four-bytes sequence character.
 
302
     *
 
303
     * @param b a byte.
 
304
     * @return true if it's the first byte of a four-bytes sequence.
 
305
     */
 
306
    private static boolean isFourBytesSequence(byte b) {
 
307
        return -16 <= b && b <= -9;
 
308
    }
 
309
 
 
310
    /**
 
311
     * If the byte has the form 11110xx, then it's the first byte of a five-bytes sequence character.
 
312
     *
 
313
     * @param b a byte.
 
314
     * @return true if it's the first byte of a five-bytes sequence.
 
315
     */
 
316
    private static boolean isFiveBytesSequence(byte b) {
 
317
        return -8 <= b && b <= -5;
 
318
    }
 
319
 
 
320
    /**
 
321
     * If the byte has the form 1110xxx, then it's the first byte of a six-bytes sequence character.
 
322
     *
 
323
     * @param b a byte.
 
324
     * @return true if it's the first byte of a six-bytes sequence.
 
325
     */
 
326
    private static boolean isSixBytesSequence(byte b) {
 
327
        return -4 <= b && b <= -3;
 
328
    }
 
329
 
 
330
    /**
 
331
     * Retrieve the default charset of the system.
 
332
     *
 
333
     * @return the default <code>Charset</code>.
 
334
     */
 
335
    public static Charset getDefaultSystemCharset() {
 
336
        return Charset.forName(System.getProperty("file.encoding"));
 
337
    }
 
338
 
 
339
    /**
 
340
     * Has a Byte Order Marker for UTF-8 (Used by Microsoft's Notepad and other editors).
 
341
     *
 
342
     * @return true if the buffer has a BOM for UTF8.
 
343
     */
 
344
    public boolean hasUTF8Bom() {
 
345
        if (buffer.length >= 3)
 
346
            return (buffer[0] == -17 && buffer[1] == -69 && buffer[2] == -65);
 
347
        else
 
348
            return false;
 
349
    }
 
350
 
 
351
    /**
 
352
     * Has a Byte Order Marker for UTF-16 Low Endian
 
353
     * (ucs-2le, ucs-4le, and ucs-16le).
 
354
     *
 
355
     * @return true if the buffer has a BOM for UTF-16 Low Endian.
 
356
     */
 
357
    public boolean hasUTF16LEBom() {
 
358
        if (buffer.length >= 2)
 
359
            return (buffer[0] == -1 && buffer[1] == -2);
 
360
        else
 
361
            return false;
 
362
    }
 
363
 
 
364
    /**
 
365
     * Has a Byte Order Marker for UTF-16 Big Endian
 
366
     * (utf-16 and ucs-2).
 
367
     *
 
368
     * @return true if the buffer has a BOM for UTF-16 Big Endian.
 
369
     */
 
370
    public boolean hasUTF16BEBom() {
 
371
        if (buffer.length >= 2)
 
372
            return (buffer[0] == -2 && buffer[1] == -1);
 
373
        else
 
374
            return false;
 
375
    }
 
376
 
 
377
    /**
 
378
     * Gets a <code>BufferedReader</code> (indeed a <code>LineNumberReader</code>) from the <code>File</code>
 
379
     * specified in the constructor of <code>CharsetToolkit</code> using the charset discovered by the
 
380
     * method <code>guessEncoding()</code>.
 
381
     *
 
382
     * @return a <code>BufferedReader</code>
 
383
     * @throws FileNotFoundException if the file is not found.
 
384
     */
 
385
    public BufferedReader getReader() throws FileNotFoundException {
 
386
        LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), getCharset()));
 
387
        if (hasUTF8Bom() || hasUTF16LEBom() || hasUTF16BEBom()) {
 
388
            try {
 
389
                reader.read();
 
390
            }
 
391
            catch (IOException e) {
 
392
                // should never happen, as a file with no content
 
393
                // but with a BOM has at least one char
 
394
            }
 
395
        }
 
396
        return reader;
 
397
    }
 
398
 
 
399
    /**
 
400
     * Retrieves all the available <code>Charset</code>s on the platform,
 
401
     * among which the default <code>charset</code>.
 
402
     *
 
403
     * @return an array of <code>Charset</code>s.
 
404
     */
 
405
    public static Charset[] getAvailableCharsets() {
 
406
        Collection collection = Charset.availableCharsets().values();
 
407
        return (Charset[]) collection.toArray(new Charset[collection.size()]);
 
408
    }
 
409
}