source: josm/trunk/src/org/openstreetmap/josm/io/UTFInputStreamReader.java@ 6524

Last change on this file since 6524 was 6362, checked in by Don-vip, 10 years ago

Checkstyle:

  • private constructors for util classes
  • final classes
  • missing "else" statements
  • import cleanup
  • Property svn:eol-style set to native
File size: 2.3 KB
Line 
1// License: GPL. See LICENSE file for details.
2package org.openstreetmap.josm.io;
3
4import java.io.IOException;
5import java.io.InputStream;
6import java.io.InputStreamReader;
7import java.io.PushbackInputStream;
8import java.io.UnsupportedEncodingException;
9
10/**
11 * Detects the different UTF encodings from byte order mark
12 */
13public final class UTFInputStreamReader extends InputStreamReader {
14
15 /**
16 * converts input stream to reader
17 * @param defaultEncoding Used, when no BOM was recognized. Can be null.
18 * @return A reader with the correct encoding. Starts to read after the BOM.
19 */
20 public static UTFInputStreamReader create(InputStream input, String defaultEncoding) throws IOException {
21 byte[] bom = new byte[4];
22 String encoding = defaultEncoding;
23 int unread;
24 PushbackInputStream pushbackStream = new PushbackInputStream(input, 4);
25 int n = pushbackStream.read(bom, 0, 4);
26
27 if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) {
28 encoding = "UTF-8";
29 unread = n - 3;
30 } else if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00) && (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
31 encoding = "UTF-32BE";
32 unread = n - 4;
33 } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE) && (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
34 encoding = "UTF-32LE";
35 unread = n - 4;
36 } else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
37 encoding = "UTF-16BE";
38 unread = n - 2;
39 } else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
40 encoding = "UTF-16LE";
41 unread = n - 2;
42 } else {
43 unread = n;
44 }
45
46 if (unread > 0) {
47 pushbackStream.unread(bom, (n - unread), unread);
48 } else if (unread < -1) {
49 pushbackStream.unread(bom, 0, 0);
50 }
51
52 if (encoding == null) {
53 return new UTFInputStreamReader(pushbackStream);
54 } else {
55 return new UTFInputStreamReader(pushbackStream, encoding);
56 }
57 }
58
59 private UTFInputStreamReader(InputStream in) {
60 super(in);
61 }
62 private UTFInputStreamReader(InputStream in, String cs) throws UnsupportedEncodingException {
63 super(in, cs);
64 }
65}
Note: See TracBrowser for help on using the repository browser.