自定义包装流,以行读取字节

本文介绍了一个Java程序,该程序使用InputStream实现按行读取文本的功能,并详细解释了其内部工作原理,包括如何处理不同操作系统的换行符。
package client;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
 * 以行来读取
 * @author root
 *	windows 中的以 \r\n为换行,而 Unix中则以 \n 为换行
 *	但在写程序时,以 \n windown会将其转换成 \r\n写入
 *	所以在以行读取字节时,if(ch=='\r')continue; if(ch=='\n') break;
 *在内部带缓冲的读取流,都是以 pos记录下一个 buf[pos]的位置,count记录这个buf中的有效数据,if(pos>=count),则要重新填充 buf中的数据
 *用到的就是 in.read(buf,0,buf.length)
 */
public class InputStreamLine {
    private static final byte CR = (byte)'\r';
    private static final byte LF = (byte)'\n';
    private static final int BUFFER_SIZE = 1024;
    private static byte[] buf;
    private int pos = 0;
    private int count = 0;
    private InputStream in;
    
    public InputStreamLine(InputStream in,int bufferSize) {
	this.in = in;
	buf = new byte[bufferSize];
    }
    public InputStreamLine(InputStream in) {
	this(in,BUFFER_SIZE);
    }
    public String readLine() throws IOException {
	StringBuilder sb = new StringBuilder();
	int ch = -1;
	while((ch=in.read())!=-1) {
	    if(ch==CR)
		continue;
	    if(ch==LF)
		break;
	    sb.append((char)ch);
	}
	if(sb.length()==0)return null;
	return sb.toString();
    }
    private void fill()throws IOException  {
	int len = in.read(buf,0,buf.length);
	pos = 0;
	count = 0;
	if(len>count)
	    count = len;
    }
    public int read() throws IOException {
	if(pos>=count)
	    fill();
	if(pos>=count)
	    return -1;
	return buf[pos++] & 0xff;
    }
    public static void main(String args[])throws IOException  {
	ByteArrayInputStream in = new ByteArrayInputStream("aaaa\nbbbbb\ncccc\n".getBytes());
	InputStreamLine inl = new InputStreamLine(in,3);
	int ch;
	while((ch=inl.read())!=-1) {
	    System.out.println(ch);
	}
    }
}	


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值