JAVA讀取很大的TXT文件(上百G)
點擊上方藍色字體,選擇“標(biāo)星公眾號”
優(yōu)質(zhì)文章,第一時間送達
? 作者?|??UnmatchedSelf
來源 |? urlify.cn/NNBN7n
當(dāng)文件過于大的時候我們?nèi)绻€用傳統(tǒng)的方式讀取很容易造成內(nèi)存滿我們應(yīng)該拆開讀?。?/p>
用NIO方式把大文件分成固定大小的小文件(小于2G,自己綜合分析設(shè)置多大,每個文件太大容易浪費空間,太小浪費時間),然后再循環(huán)用方案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,?然后在用傳統(tǒng)的方法去讀取即可
??????}?catch?(Exception?e)?{
??????}
}
?
粉絲福利:Java從入門到入土學(xué)習(xí)路線圖
???

?長按上方微信二維碼?2 秒
感謝點贊支持下哈?
評論
圖片
表情
