Java中超大文件讀寫


如果文件過大不能一次加載,就可以利用緩沖區:

File file = new File(filepath);   
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));    
BufferedReader reader = new BufferedReader(new InputStreamReader(fis,"utf-8"),10*1024*1024);// 用10M的緩沖讀取文本文件  
  
String line = "";
while((line = reader.readLine()) != null){
   //TODO: write your business
}

還可以用RandomAccessFile類讀取,進行分段批操作:

String path = "你要讀的文件的路徑";
        RandomAccessFile br = new RandomAccessFile(path, "rw");
        String str = null, app = null;
        int i = 0;
        while ((str = br.readLine()) != null) {
            i++;
            app = app + str;
            if (i >= 100) {// 假設讀取100行
                i = 0;
                // 這里你先對這100行操作,然后繼續讀
                app = null;
            }
        }
        br.close();
    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM