import java.io.Reader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.EOFException; import java.io.CharConversionException; import java.io.UnsupportedEncodingException; /** * AutoInputStreamReader is like InputStreamReader, but detects the used * character encoding automatically, from a list of possible choices. * * @author Fredrik Roubert * @version 21 March 2003 * * @see java.io.InputStreamReader */ public class AutoInputStreamReader extends Reader { protected InputStreamReader isr; AutoInputStreamReader(InputStream is, String encs[]) throws IOException, UnsupportedEncodingException { ByteArrayInputStream bais; byte buf[]; int len; if ((len = is.available()) < 1) throw new EOFException(); buf = new byte[len]; if (is.read(buf) < 1) throw new EOFException(); is.close(); bais = new ByteArrayInputStream(buf); for (int i = 0; i < encs.length; i ++) { isr = new InputStreamReader(bais, encs[i]); try { while (isr.read() != -1) ; } catch (CharConversionException e) { bais.reset(); isr.close(); continue; } bais.reset(); isr.close(); isr = new InputStreamReader(bais, encs[i]); return; } throw new UnsupportedEncodingException(); } public String getEncoding() { return isr.getEncoding(); } public void close() throws IOException { isr.close(); } public void mark(int readAheadLimit) throws IOException { isr.mark(readAheadLimit); } public boolean markSupported() { return isr.markSupported(); } public int read() throws IOException { return isr.read(); } public int read(char[] cbuf) throws IOException { return isr.read(cbuf); } public int read(char[] cbuf, int off, int len) throws IOException { return isr.read(cbuf, off, len); } public boolean ready() throws IOException { return isr.ready(); } public void reset() throws IOException { isr.reset(); } public long skip(long n) throws IOException { return isr.skip(n); } }