public void read() throws IOException{
FileLineDataHandler handler = new FileLineDataHandler();//数据处理类
ByteBuffer buffer = ByteBuffer.allocate(200);//保证该缓冲区至少装得下一行
int position = 0;//设置通道指针的位置
byte[] b = buffer.array();
byte defaultVal = 0;
while(this.channel.read(buffer)>-1){
buffer.flip();
for(int i = 0;i<b.length;i++){
//判断每个字节是不是换行符
if(b[i]==13) {
Arrays.fill(b, i,b.length,defaultVal);//清空换行符后面的内容
position += 2;//windows 每行结尾有两个字节 13 10 所以加2
this.channel.position(position);//将通道指针位置设置为第二行第一个字节的位置
handler.process(b);
break;
}
position++;//每次判断 指针位置+1
//如果是最后一行 (最后一行没有换行符)
if(position == this.channel.size()){
handler.process(b);
}
}
}
}
nio按行读取 自认为代码挺少的
最新推荐文章于 2023-08-07 17:37:00 发布