java如何讀取超大文件
Java NIO讀取大文件已經(jīng)不是什么新鮮事了,但根據(jù)網(wǎng)上示例寫出的代碼來處理具體的業(yè)務(wù)總會出現(xiàn)一些奇怪的Bug。
針對這種情況,我總結(jié)了一些容易出現(xiàn)Bug的經(jīng)驗
1.編碼格式
由于是使用NIO讀文件通道的方式,拿到的內(nèi)容都是byte[],在生成String對象時一定要設(shè)置與讀取文件相同的編碼,而不是項目編碼。
2.換行符
一般在業(yè)務(wù)中,多數(shù)情況都是讀取文本文件,在解析byte[]時發(fā)現(xiàn)有換行符時則認(rèn)為該行已經(jīng)結(jié)束。
在我們寫Java程序時,大多數(shù)都認(rèn)為\r\n為一個文本的一行結(jié)束,但這個換行符根據(jù)當(dāng)前系統(tǒng)的不同,換行符也不相同,比如在Linux/Unix下?lián)Q行符是\n,而在Windows下則是\r\n。如果將換行符定為\r\n,在讀取由Linux系統(tǒng)生成的文本文件則會出現(xiàn)亂碼。
3.讀取正常,但中間偶爾會出現(xiàn)亂碼
public static void main(String[] args) throws Exception { int bufSize = 1024; byte[] bs = new byte[bufSize]; ByteBuffer byteBuf = ByteBuffer.allocate(1024); FileChannel channel = new RandomAccessFile("d:\\filename","r").getChannel(); while(channel.read(byteBuf) != -1) { int size = byteBuf.position(); byteBuf.rewind(); byteBuf.get(bs); // 把文件當(dāng)字符串處理,直接打印做為一個例子。 System.out.print(new String(bs, 0, size)); byteBuf.clear(); } }
這是網(wǎng)上大多數(shù)使用NIO來讀取大文件的例子,但這有個問題。中文字符根據(jù)編碼不同,會占用2到3個字節(jié),而上面程序中每次都讀取1024個字節(jié),那這樣就會出現(xiàn)一個問題,如果該文件中第1023,1024,1025三個字節(jié)是一個漢字,那么一次讀1024個字節(jié)就會將這個漢字切分成兩瓣,生成String對象時就會出現(xiàn)亂碼。
解決思路是判斷這讀取的1024個字節(jié),最后一位是不是\n,如果不是,那么將最后一個\n以后的byte[]緩存起來,加到下一次讀取的byte[]頭部。
以下為代碼結(jié)構(gòu):
NioFileReader
package com.okey.util; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * Created with Okey * User: Okey * Date: 13-3-14 * Time: 上午11:29 * 讀取文件工具 */ public class NIOFileReader { // 每次讀取文件內(nèi)容緩沖大小,默認(rèn)為1024個字節(jié) private int bufSize = 1024; // 換行符 private byte key = "\n".getBytes()[0]; // 當(dāng)前行數(shù) private long lineNum = 0; // 文件編碼,默認(rèn)為gb2312 private String encode = "gb2312"; // 具體業(yè)務(wù)邏輯監(jiān)聽器 private ReaderListener readerListener; /** * 設(shè)置回調(diào)方法 * @param readerListener */ public NIOFileReader(ReaderListener readerListener) { this.readerListener = readerListener; } /** * 設(shè)置回調(diào)方法,并指明文件編碼 * @param readerListener * @param encode */ public NIOFileReader(ReaderListener readerListener, String encode) { this.encode = encode; this.readerListener = readerListener; } /** * 普通io方式讀取文件 * @param fullPath * @throws Exception */ public void normalReadFileByLine(String fullPath) throws Exception { File fin = new File(fullPath); if (fin.exists()) { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fin), encode)); String lineStr; while ((lineStr = reader.readLine()) != null) { lineNum++; readerListener.outLine(lineStr.trim(), lineNum, false); } readerListener.outLine(null, lineNum, true); reader.close(); } } /** * 使用NIO逐行讀取文件 * * @param fullPath * @throws java.io.FileNotFoundException */ public void readFileByLine(String fullPath) throws Exception { File fin = new File(fullPath); if (fin.exists()) { FileChannel fcin = new RandomAccessFile(fin, "r").getChannel(); try { ByteBuffer rBuffer = ByteBuffer.allocate(bufSize); // 每次讀取的內(nèi)容 byte[] bs = new byte[bufSize]; // 緩存 byte[] tempBs = new byte[0]; String line = ""; while (fcin.read(rBuffer) != -1) { int rSize = rBuffer.position(); rBuffer.rewind(); rBuffer.get(bs); rBuffer.clear(); byte[] newStrByte = bs; // 如果發(fā)現(xiàn)有上次未讀完的緩存,則將它加到當(dāng)前讀取的內(nèi)容前面 if (null != tempBs) { int tL = tempBs.length; newStrByte = new byte[rSize + tL]; System.arraycopy(tempBs, 0, newStrByte, 0, tL); System.arraycopy(bs, 0, newStrByte, tL, rSize); } int fromIndex = 0; int endIndex = 0; // 每次讀一行內(nèi)容,以 key(默認(rèn)為\n) 作為結(jié)束符 while ((endIndex = indexOf(newStrByte, fromIndex)) != -1) { byte[] bLine = substring(newStrByte, fromIndex, endIndex); line = new String(bLine, 0, bLine.length, encode); lineNum++; // 輸出一行內(nèi)容,處理方式由調(diào)用方提供 readerListener.outLine(line.trim(), lineNum, false); fromIndex = endIndex + 1; } // 將未讀取完成的內(nèi)容放到緩存中 tempBs = substring(newStrByte, fromIndex, newStrByte.length); } // 將剩下的最后內(nèi)容作為一行,輸出,并指明這是最后一行 String lineStr = new String(tempBs, 0, tempBs.length, encode); readerListener.outLine(lineStr.trim(), lineNum, true); } catch (Exception e) { e.printStackTrace(); } finally { fcin.close(); } } else { throw new FileNotFoundException("沒有找到文件:" + fullPath); } } /** * 查找一個byte[]從指定位置之后的一個換行符位置 * @param src * @param fromIndex * @return * @throws Exception */ private int indexOf(byte[] src, int fromIndex) throws Exception { for (int i = fromIndex; i < src.length; i++) { if (src[i] == key) { return i; } } return -1; } /** * 從指定開始位置讀取一個byte[]直到指定結(jié)束位置為止生成一個全新的byte[] * @param src * @param fromIndex * @param endIndex * @return * @throws Exception */ private byte[] substring(byte[] src, int fromIndex, int endIndex) throws Exception { int size = endIndex - fromIndex; byte[] ret = new byte[size]; System.arraycopy(src, fromIndex, ret, 0, size); return ret; } }
ReaderListener
package com.okey.util; import java.util.ArrayList; import java.util.List; /** * Created with Okey * User: Okey * Date: 13-3-14 * Time: 下午3:19 * NIO逐行讀數(shù)據(jù)回調(diào)方法 */ public abstract class ReaderListener { // 一次讀取行數(shù),默認(rèn)為500 private int readColNum = 500; private List<String> list = new ArrayList<String>(); /** * 設(shè)置一次讀取行數(shù) * @param readColNum */ protected void setReadColNum(int readColNum) { this.readColNum = readColNum; } /** * 每讀取到一行數(shù)據(jù),添加到緩存中 * @param lineStr 讀取到的數(shù)據(jù) * @param lineNum 行號 * @param over 是否讀取完成 * @throws Exception */ public void outLine(String lineStr, long lineNum, boolean over) throws Exception { if(null != lineStr) list.add(lineStr); if (!over && (lineNum % readColNum == 0)) { output(list); list.clear(); } else if (over) { output(list); list.clear(); } } /** * 批量輸出 * * @param stringList * @throws Exception */ public abstract void output(List<String> stringList) throws Exception; }
ReadTxt(具體業(yè)務(wù)邏輯)
package com.okey.util; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created with IntelliJ IDEA. * User: Okey * Date: 14-3-6 * Time: 上午11:02 * To change this template use File | Settings | File Templates. */ public class ReadTxt { public static void main(String[] args) throws Exception{ String filename = "E:/address_city.utf8.txt"; ReaderListener readerListener = new ReaderListener() { @Override public void output(List<String> stringList) throws Exception { for (String s : stringList) { System.out.println("s = " + s); } } }; readerListener.setReadColNum(100000); NIOFileReader nioFileReader = new NIOFileReader(readerListener,"utf-8"); nioFileReader.readFileByLine(filename); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis 入門之MyBatis環(huán)境搭建(第一篇)
Mybatis的前身叫iBatis,本是apache的一個開源項目, 2010年這個項目由apache software foundation 遷移到了google code,并且改名為MyBatis。這篇文章主要介紹了Mybatis入門第一篇之MyBaits環(huán)境搭建,需要的朋友參考下2016-12-12解決mapper.xml中resultType映射類型的問題
這篇文章主要介紹了解決mapper.xml中resultType映射類型的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06MyBatis實現(xiàn)簡單的數(shù)據(jù)表分月存儲
本文主要介紹了MyBatis實現(xiàn)簡單的數(shù)據(jù)表分月存儲,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03解析ConcurrentHashMap:成員屬性、內(nèi)部類、構(gòu)造方法
ConcurrentHashMap是由Segment數(shù)組結(jié)構(gòu)和HashEntry數(shù)組結(jié)構(gòu)組成。Segment的結(jié)構(gòu)和HashMap類似,是一種數(shù)組和鏈表結(jié)構(gòu),今天給大家普及java面試常見問題---ConcurrentHashMap知識,一起看看吧2021-06-06Springboot如何設(shè)置靜態(tài)資源緩存一年
這篇文章主要介紹了Springboot如何設(shè)置靜態(tài)資源緩存一年,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11java socket大數(shù)據(jù)傳輸丟失問題及解決
這篇文章主要介紹了java socket大數(shù)據(jù)傳輸丟失問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08