Java讀取文件 利用MappedByteBuffer進行緩衝,這樣能夠保證邊讀取大文件,邊進行處理
java
package sean; import java.io.ByteArrayInputStream; import java.io.File; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.Scanner; public class Snippet { public void readResource() { long fileLength = 0; final int BUFFER_SIZE = 0x300000;// 3M的緩衝 //for (String fileDirectory : this.readResourceDirectory())// 獲得文件存放路徑,我這裏使用了一個方法從XML文件中讀出文件的 // 存放路徑,固然也能夠用絕對路徑來代替這裏的fileDriectory //{ File file = new File("D:\\MyData.txt"); fileLength = file.length(); try { MappedByteBuffer inputBuffer = new RandomAccessFile(file, "r") .getChannel().map(FileChannel.MapMode.READ_ONLY, 0, fileLength);// 讀取大文件 byte[] dst = new byte[BUFFER_SIZE];// 每次讀出3M的內容 for (int offset = 0; offset < fileLength; offset += BUFFER_SIZE) { if (fileLength - offset >= BUFFER_SIZE) { for (int i = 0; i < BUFFER_SIZE; i++) dst[i] = inputBuffer.get(offset + i); } else { for (int i = 0; i < fileLength - offset; i++) dst[i] = inputBuffer.get(offset + i); } // 將獲得的3M內容給Scanner,這裏的XXX是指Scanner解析的分隔符 Scanner scan = new Scanner(new ByteArrayInputStream(dst)) .useDelimiter(" "); while (scan.hasNext()) { // 這裏爲對讀取文本解析的方法 System.out.print(scan.next() + " "); } scan.close(); } } catch (Exception e) { e.printStackTrace(); } //} } public static void main(String[] args) { Snippet sp = new Snippet(); sp.readResource(); } }