當文件過於大的時候我們如果還用傳統的方式讀取很容易造成內存滿我們應該拆開讀取:
用NIO方式把大文件分成固定大小的小文件(小於2G,自己綜合分析設置多大,每個文件太大容易浪費空間,太小浪費時間),然后再循環用方案1去讀每個小文件。
public static void readLargeTextWithNIO() {
try {
long startTime = System.currentTimeMillis();
// 要讀取的文件
FileInputStream fin = new FileInputStream("/Applications/demo/aaaa.txt");
FileChannel fcin = fin.getChannel();
// 文件過大拆分成 128M 大小的txt文件
ByteBuffer buffer = ByteBuffer.allocate(128 * 1024 * 1024);
while (true) {
buffer.clear();
int flag = fcin.read(buffer);
if (flag == -1) {
break;
}
buffer.flip();
// 輸出到指定的位置
FileOutputStream fileInputStream = new FileOutputStream("/Applications/demo/"+ UUID.randomUUID().toString()+".txt");
FileChannel channel = fileInputStream.getChannel();
channel.write(buffer);
}
long endTime = System.currentTimeMillis();
System.out.println(" 共消耗:" + (endTime-startTime) / 1000 +"秒");
// 分割成了 每一個文件 大小是 128M, 然后在用傳統的方法去讀取即可
} catch (Exception e) {
}
}