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);
}
}
}