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.CharsetEncoder ; 45 import java.nio.charset.CoderResult ; 46 47 52 public class CharsetEncoderInputStream extends FilterInputStream { 53 54 private Charset charset; 55 private CharsetEncoder encoder; 56 57 private CharBuffer inBytes; 58 private ByteBuffer outBytes; 59 60 private int pos; 61 private int available; 62 63 69 public CharsetEncoderInputStream(InputStream arg0, Charset charset) { 70 super(arg0); 71 this.charset = charset; 72 encoder = charset.newEncoder(); 73 74 inBytes = CharBuffer.allocate(1); 75 outBytes = ByteBuffer.allocate(5); 76 } 77 78 84 private int encodeNextCharacter() throws IOException { 85 int read = in.read(); 86 87 if( read == -1) return -1; 88 89 inBytes.clear(); 90 inBytes.put(0,(char) read); 91 92 outBytes.clear(); 93 CoderResult result = encoder.encode( inBytes, outBytes, in.available() == 0 ); 94 95 if( result.isMalformed() || result.isUnmappable() ) { 97 outBytes.put((byte)0); 98 return outBytes.limit(); 99 } 100 101 return outBytes.position(); 102 } 103 104 107 public int read() throws IOException { 108 if( pos == available ) { 109 available = encodeNextCharacter(); 110 pos = 0; 111 } 112 113 if( available == -1) return -1; 114 115 return outBytes.get(pos++); 116 } 117 118 121 public int read(byte[] arg0, int arg1, int arg2) throws IOException { 122 int next; 123 for( int i=0; i<arg2; i++) { 124 next = read(); 125 if( next == -1 ) { 126 if( i == 0 ) { 127 return -1; 128 } else { 129 return i; 130 } 131 } 132 arg0[arg1+i] = (byte) next; 133 } 134 return arg2; 135 } 136 137 138 } 139 | Popular Tags |