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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM