1 7 8 package test; 9 10 import java.io.*; 11 12 20 public class UTF8BOMSkipper 21 extends FilterInputStream { 22 23 27 28 private boolean fStart = true; 29 30 31 private int fOffset; 32 33 34 private int[] fFirst3Bytes; 35 36 40 41 public UTF8BOMSkipper(InputStream stream) { 42 super(stream); 43 } 45 49 50 public int read() throws IOException { 51 52 if (fStart) { 54 fStart = false; 55 int b1 = super.read(); 56 int b2 = super.read(); 57 int b3 = super.read(); 58 if (b1 != 0xEF || b2 != 0xBB || b3 != 0xBF) { 59 fFirst3Bytes = new int[3]; 60 fFirst3Bytes[0] = b1; 61 fFirst3Bytes[1] = b2; 62 fFirst3Bytes[2] = b3; 63 } 64 } 65 66 if (fFirst3Bytes != null) { 68 int b = fFirst3Bytes[fOffset++]; 69 if (fOffset == fFirst3Bytes.length) { 70 fFirst3Bytes = null; 71 } 72 return b; 73 } 74 75 return super.read(); 77 78 } 80 81 public int read(byte[] buffer, int offset, int length) throws IOException { 82 83 if (fStart || fFirst3Bytes != null) { 84 for (int i = 0; i < length; i++) { 85 int b = this.read(); 86 if (b == -1) { 87 return i > 0 ? i : -1; 88 } 89 buffer[offset + i] = (byte)b; 90 } 91 return length; 92 } 93 94 return super.read(buffer, offset, length); 95 96 } 98 99 public boolean markSupported() { 100 return false; 101 } 103 104 public int available() throws IOException { 105 if (fFirst3Bytes != null) { 106 return fFirst3Bytes.length - fOffset; 107 } 108 return super.available(); 109 } 111 } | Popular Tags |