1 36 package org.columba.ristretto.coder; 37 38 import java.io.FilterInputStream ; 39 import java.io.IOException ; 40 import java.io.InputStream ; 41 import java.nio.ByteBuffer ; 42 import java.nio.CharBuffer ; 43 import java.nio.charset.Charset ; 44 import java.nio.charset.CharsetDecoder ; 45 import java.nio.charset.CoderResult ; 46 import java.nio.charset.CodingErrorAction ; 47 48 53 public class CharsetDecoderInputStream extends FilterInputStream { 54 55 private Charset charset; 56 private CharsetDecoder decoder; 57 58 private ByteBuffer inBytes; 59 private CharBuffer outBytes; 60 61 67 public CharsetDecoderInputStream(InputStream arg0, Charset charset) { 68 super(arg0); 69 this.charset = charset; 70 decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE); 71 72 inBytes = ByteBuffer.allocate(5); 73 outBytes = CharBuffer.allocate(1); 74 } 75 76 83 private int decodeNextChar() throws IOException { 84 CoderResult result; 85 int read; 86 87 88 inBytes.clear(); 89 inBytes.limit(1); 90 91 read = in.read(); 92 if( read == -1) return -1; 93 inBytes.put( 0, (byte) read ); 94 95 outBytes.clear(); 96 result = decoder.decode(inBytes, outBytes, in.available() == 0); 97 98 99 while( outBytes.position() == 0 ) { 101 read = in.read(); 102 if( read == -1) return -1; 103 inBytes.limit(inBytes.limit()+1); 104 inBytes.put(inBytes.limit()-1,(byte) read); 105 106 outBytes.clear(); 107 result = decoder.decode(inBytes, outBytes, in.available() == 0); 108 } 109 110 return outBytes.position(); 111 } 112 113 114 117 public int read() throws IOException { 118 if( decodeNextChar() == -1) return -1; 119 120 return outBytes.get(0); 121 } 122 123 126 public int read(byte[] arg0, int arg1, int arg2) throws IOException { 127 int next; 128 for( int i=0; i<arg2; i++) { 129 next = read(); 130 if( next == -1 ) { 131 if( i == 0 ) { 132 return -1; 133 } else { 134 return i; 135 } 136 } 137 arg0[arg1+i] = (byte) next; 138 } 139 return arg2; 140 } 141 142 143 } 144 | Popular Tags |