InputStreamReader.java [plain text]
package java.io;
import gnu.gcj.convert.*;
public class InputStreamReader extends Reader
{
BufferedInputStream in;
char[] work;
int wpos;
int wcount;
BytesToUnicode converter;
public InputStreamReader(InputStream in)
{
this(in, BytesToUnicode.getDefaultDecoder());
}
public InputStreamReader(InputStream in, String enc)
throws UnsupportedEncodingException
{
this(in, BytesToUnicode.getDecoder(enc));
}
private InputStreamReader(InputStream in, BytesToUnicode decoder)
{
this.in = in instanceof BufferedInputStream
? (BufferedInputStream) in
: new BufferedInputStream(in);
this.lock = in;
converter = decoder;
converter.setInput(this.in.buf, 0, 0);
}
public void close() throws IOException
{
synchronized (lock)
{
if (in != null)
in.close();
in = null;
work = null;
wpos = wcount = 0;
}
}
public String getEncoding() { return converter.getName(); }
public boolean ready() throws IOException
{
synchronized (lock)
{
if (in == null)
throw new IOException("Stream closed");
if (wpos < wcount)
return true;
return in.available () > 0;
}
}
public int read(char buf[], int offset, int length) throws IOException
{
synchronized (lock)
{
if (in == null)
throw new IOException("Stream closed");
if (length == 0)
return 0;
int wavail = wcount - wpos;
if (wavail <= 0)
{
if (! refill ())
return -1;
wavail = wcount - wpos;
}
if (length > wavail)
length = wavail;
System.arraycopy(work, wpos, buf, offset, length);
wpos += length;
return length;
}
}
public int read() throws IOException
{
synchronized (lock)
{
if (in == null)
throw new IOException("Stream closed");
int wavail = wcount - wpos;
if (wavail <= 0)
{
if (! refill ())
return -1;
}
return work[wpos++];
}
}
private boolean refill () throws IOException
{
wcount = wpos = 0;
if (work == null)
work = new char[100];
for (;;)
{
in.mark (0);
boolean r = in.pos < in.count || in.refill ();
in.reset ();
if (! r)
return false;
converter.setInput(in.buf, in.pos, in.count);
int count = converter.read (work, wpos, work.length - wpos);
in.skip(converter.inpos - in.pos);
if (count > 0)
{
wcount += count;
return true;
}
}
}
}