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