62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
public class ReaderInputStream extends InputStream {
private final Reader r;
private final String encoding;
private byte[] buf;
private final char[] cBuf = new char[1];
private int len;
public ReaderInputStream(Reader r, String encoding) {
this.r = r;
this.encoding = encoding;
}
@Override
public int read() throws IOException {
if (len == 0) {
int ch = r.read();
if (ch < 0)
return -1;
cBuf[0] = (char) ch;
buf = new String(cBuf).getBytes(encoding);
len = buf.length;
}
return buf[--len] & 0xFF;
}
@Override
public void close() throws IOException {
super.close();
r.close();
}
}
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class WriterOutputStream extends OutputStream {
private final Writer w;
private final String encoding;
private final byte[] buf = new byte[128];
private int size;
public WriterOutputStream(Writer w, String encoding) {
this.w = w;
this.encoding = encoding;
}
@Override
public void write(int b) throws IOException {
if (size == buf.length)
flush();
buf[size++] = (byte) b;
}
@Override
public void flush() throws IOException {
super.flush();
String s = null;
int len;
for (len = size; len > 0; len--) {
try {
s = new String(buf, 0, len, encoding);
} catch (UnsupportedEncodingException ue) {
continue;
}
break;
}
if (s != null) {
w.write(s);
size -= len;
System.arraycopy(buf, len, buf, 0, size);
}
}
}