Java实现按行读取大文件

非频繁操作如下:

String file = "F:" + File.separator + "a.txt";
FileInputStream fis = new FileInputStream(file);
RandomAccessFile raf = new RandomAccessFile(new File(file),"r");
String s ;
while((s =raf.readLine())!=null){
System.out.println(s);
}
raf.close();
fis.close();

可考虑bufferedinputstream和bufferedoutputstream来字节读取,上面这个代码太简单了,适用于非频繁操作。可以采用nio的FileChannel,比较适合于高并发操作,如下为filechannel的部分代码:

File inFile = new File("D:\\error");
 File outFile = new File("D:\\to.txt");
  
 FileChannel inFileChannel = new FileInputStream(inFile).getChannel();
 FileChannel outFileChannel = new FileOutputStream(outFile).getChannel();
  
 ByteBuffer buffer = ByteBuffer.allocate(1024);
 while(-1 != inFileChannel.read(buffer)){
  buffer.flip();
  outFileChannel.write(buffer);
  buffer.clear();
 }
 outFileChannel.close();
 inFileChannel.close();

 

参考:https://www.jb51.net/article/66021.htm

 

posted @ 2020-03-12 11:53  007少侠  阅读(3943)  评论(0编辑  收藏  举报
友情链接:便宜vps(CN2GIA线路)
站长统计: