import java.io.Fileimport java.io.FileInputStreamimport java.io.FileOutputStreamimport java.io.IOExceptionimport java.io.OutputStreamimport java.nio.ByteBufferimport java.nio.channels.FileChannelpublic class FileChannelDemo { public static void main(String[] args) throws IOException { File in = new File("D:\\in.txt")File out = new File("D:\\out.txt")if(in.createNewFile()){ System.out.println("in.txt被创建")FileOutputStream is = new FileOutputStream(in)byte[] b = "激冲我一正瞎定明清歼能行的".getBytes()is.write(b, 0, b.length)} if(out.createNewFile()){ System.out.println("out.txt被创建")} FileInputStream is = new FileInputStream(in)FileOutputStream os = new FileOutputStream(out)FileChannel fis = is.getChannel()FileChannel fos = os.getChannel()ByteBuffer bytedata = ByteBuffer.allocate(100)while(fis.read(bytedata)!= -1){ //通过通道读写交叉进行。 bytedata.flip()fos.write(bytedata)bytedata.clear()} fis.close()fos.close()is.close()os.close()} }
利用java.nio的FileChannel能够实现按腊塌行读取文件:
具体思路是:设置两个缓冲区,一大一小,大的缓冲区为每次读取的量,小的缓冲区存放每行的数据(确保大小可存放文本中最长的那行)。读取的时候判断是不是换行符13,是的话则返回一行数据,不是的话继续读取,直到读完文件。
实现方法:
皮局拦 FileChannel fc=raf.getChannel()
//一次读取文件,读取的字节缓存数
ByteBuffer fbb=ByteBuffer.allocate(1024*5)
fc.read(fbb)
fbb.flip()
//每行缓存的字节 根据你的实际需求
ByteBuffer bb=ByteBuffer.allocate(500)
燃胡 //判断是否读完文件
public boolean hasNext() throws IOException {
if(EOF)return false
if(fbb.position()==fbb.limit()){//判断当前位置是否到了缓冲区的限制
if(readByte()==0) return false
}
while(true){
if(fbb.position()==fbb.limit()){
if(readByte()==0) break
}
byte a=fbb.get()
if(a==13){
if(fbb.position()==fbb.limit()){
if(readByte()==0) break
}
return true
}else{
if (bb.position() < bb.limit()) {
bb.put(a)
}else {
if(readByte()==0) break
}
}
}
return true
}
评论列表(0条)