- import java.io.*;
- /**
- * 在Java中,输入流分为字节流和字符流,字节流向字符流的转换有现成的类可以使用
- * 但是字符流再转回 字节流就不好办了,这里提供一个字符输入流向字节输入流的转换
- * @author redduke1202
- */
- public class InputStreamFromReader extends InputStream {
- /*
- * 字符输入流
- */
- Reader reader;
- /*
- * 编码格式
- */
- String encoding=null;
- /*
- * 字节缓冲,单个字符最多占用4个字节
- */
- byte[] buf=null;
- /*
- * 缓冲字节大小
- */
- int bufSize=0;
- /*
- * 构造方法,通过字符流构造字节流
- */
- public InputStreamFromReader(Reader reader)
- {
- this.reader=reader;
- }
- /*
- * 构造方法,指定字符流和编码格式
- */
- public InputStreamFromReader(Reader reader,String encoding)
- {
- this.reader=reader;
- this.encoding=encoding;
- }
- @Override
- /*
- * 读取单个字节
- */
- public int read() throws IOException {
- if(bufSize<1)//缓冲中无数据,填充缓冲数组
- {
- int ch=reader.read();//读取下一个字符
- if(ch==-1) //结束
- return -1;
- String temp=new String(new char[]{(char)ch});//构造字符串
- //根据编码获取字节数组,放在字节缓冲中
- if(this.encoding==null)
- this.buf=temp.getBytes();
- else
- this.buf=temp.getBytes(this.encoding);
- this.bufSize=this.buf.length;
- }
- //从缓冲中返回
- return buf[bufSize--]&0xff;
- }
- }
字符输入流向字节输入流的转换
最新推荐文章于 2023-12-19 13:51:02 发布