1 28 29 package com.caucho.vfs; 30 31 import java.io.IOException ; 32 import java.io.InputStream ; 33 import java.io.Reader ; 34 import java.io.UnsupportedEncodingException ; 35 36 51 abstract public class AbstractByteToChar extends InputStream { 52 private Reader _readEncoding; 53 private String _readEncodingName; 54 private int _specialEncoding; 55 56 private final byte []_byteBuffer = new byte[256]; 57 private final char []_charBuffer = new char[1]; 58 private int _byteHead; 59 private int _byteTail; 60 61 64 AbstractByteToChar() 65 { 66 } 67 68 71 public void setEncoding(String encoding) 72 throws UnsupportedEncodingException 73 { 74 if (encoding != null) { 75 _readEncoding = Encoding.getReadEncoding(this, encoding); 76 _readEncodingName = Encoding.getMimeName(encoding); 77 } 78 else { 79 _readEncoding = null; 80 _readEncodingName = null; 81 } 82 } 83 84 87 public void clear() 88 { 89 _byteHead = 0; 90 _byteTail = 0; 91 } 92 93 98 public void addByte(int b) 99 throws IOException 100 { 101 int nextHead = (_byteHead + 1) % _byteBuffer.length; 102 103 while (nextHead == _byteTail) { 104 int ch = readChar(); 105 106 if (ch < 0) 107 break; 108 109 outputChar(ch); 110 } 111 112 _byteBuffer[_byteHead] = (byte) b; 113 _byteHead = nextHead; 114 } 115 116 121 public void addChar(char nextCh) 122 throws IOException 123 { 124 int ch; 125 while ((ch = readChar()) >= 0) 126 outputChar((char) ch); 127 128 outputChar(nextCh); 129 } 130 131 134 public void flush() 135 throws IOException 136 { 137 int ch; 138 while ((ch = readChar()) >= 0) 139 outputChar((char) ch); 140 } 141 142 145 private int readChar() 146 throws IOException 147 { 148 Reader readEncoding = _readEncoding; 149 150 if (readEncoding == null) 151 return read(); 152 else { 153 if (readEncoding.read(_charBuffer, 0, 1) < 0) 154 return -1; 155 else 156 return _charBuffer[0]; 157 } 158 } 159 160 165 public int read() 166 throws IOException 167 { 168 if (_byteHead == _byteTail) 169 return -1; 170 171 int b = _byteBuffer[_byteTail] & 0xff; 172 _byteTail = (_byteTail + 1) % _byteBuffer.length; 173 174 return b; 175 } 176 177 abstract protected void outputChar(int ch) 178 throws IOException ; 179 } 180 | Popular Tags |