java實現超大文件的讀寫功能

這篇文章主要爲大家詳細介紹了java實現超大文件的讀寫功能,具有一定的參考價值,感興趣的小夥伴們可以參考一下

對於幾百M或上G的大文件可使用java nio進行讀寫 , 根據個人的需求 可能需要將一個超大文件讀寫形成很多較小的文件進行分析,這也不是什麼難事,在讀完一個緩衝區後 更換寫入的對象即可,本文就不做詳細介紹了,有需要的可以聯繫本人。

直接上程序吧

package cn.gzu.readfile;
 import java.io.File; 
 import java.io.IOException; 
 import java.io.RandomAccessFile; 
 import java.nio.ByteBuffer; 
 import java.nio.channels.FileChannel; 
 
 
public class ReadWriteNio { 
 
public static void main(String args[]) throws Exception{ 
 int bufSize = 100; 
 File fin = new File("E:\\jiahui\\2014-09-01.dat"); 
 File fout = new File("E:\\jiahui\\res.txt"); 
 
 System.out.print("開始讀取並重寫文件,請等待...");
 
 FileChannel fcin = new RandomAccessFile(fin, "r").getChannel(); 
 ByteBuffer rBuffer = ByteBuffer.allocate(bufSize); 
 
 FileChannel fcout = new RandomAccessFile(fout, "rws").getChannel(); 
 ByteBuffer wBuffer = ByteBuffer.allocateDirect(bufSize); 
 
 readFileByLine(bufSize, fcin, rBuffer, fcout, wBuffer); 
 
 System.out.print("讀寫完成!"); 
} 
 
 /*讀文件同時寫文件*/
public static void readFileByLine(int bufSize, FileChannel fcin, ByteBuffer rBuffer, 
 FileChannel fcout, ByteBuffer wBuffer){ 
 String enterStr = "\n"; 
 try{ 
 byte[] bs = new byte[bufSize]; 
 
 int size = 0; 
 StringBuffer strBuf = new StringBuffer(""); 
 while((size = fcin.read(rBuffer)) != -1){ 
// while(fcin.read(rBuffer) != -1){ 
 if(size > 1*1024){
 break;
 }
 
 int rSize = rBuffer.position(); 
 rBuffer.rewind(); 
 rBuffer.get(bs); 
 rBuffer.clear(); 
 String tempString = new String(bs, 0, rSize,"UTF-8"); 
 // System.out.println(size+": "+tempString); 
 
 int fromIndex = 0; 
 int endIndex = 0; 
 while((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1){ 
  String line = tempString.substring(fromIndex, endIndex); 
  line = new String(strBuf.toString() + line + "\n"); 
  System.out.println(size+": "+line); 
  //System.out.print("</over/>"); 
  //write to anthone file 
  writeFileByLine(fcout, wBuffer, line); 
 
  strBuf.delete(0, strBuf.length()); 
  fromIndex = endIndex + 1; 
 } 
 if(rSize > tempString.length()){ 
  strBuf.append(tempString.substring(fromIndex, tempString.length())); 
 }else{ 
  strBuf.append(tempString.substring(fromIndex, rSize)); 
 } 
 } 
 } catch (IOException e) { 
 // TODO Auto-generated catch block 
 e.printStackTrace(); 
 } 
} 
 
 /*寫文件*/
public static void writeFileByLine(FileChannel fcout, ByteBuffer wBuffer, String line){ 
 try { 
 //write on file head 
 //fcout.write(wBuffer.wrap(line.getBytes())); 
 //wirte append file on foot 
 fcout.write(wBuffer.wrap(line.getBytes()), fcout.size()); 
 
 } catch (IOException e) { 
 // TODO Auto-generated catch block 
 e.printStackTrace(); 
 } 
} 
 
 
} 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章