這篇文章給大家分享的是有關java讀取超大文件的示例的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
成都創新互聯專注為客戶提供全方位的互聯網綜合服務,包含不限于網站制作、成都網站建設、沂源網絡推廣、小程序制作、沂源網絡營銷、沂源企業策劃、沂源品牌公關、搜索引擎seo、人物專訪、企業宣傳片、企業代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;成都創新互聯為所有大學生創業者提供沂源建站搭建服務,24小時服務熱線:13518219792,官方網址:www.yijiale78.com
Java NIO讀取大文件已經不是什么新鮮事了,但根據網上示例寫出的代碼來處理具體的業務總會出現一些奇怪的Bug。
針對這種情況,我總結了一些容易出現Bug的經驗
1.編碼格式
由于是使用NIO讀文件通道的方式,拿到的內容都是byte[],在生成String對象時一定要設置與讀取文件相同的編碼,而不是項目編碼。
2.換行符
一般在業務中,多數情況都是讀取文本文件,在解析byte[]時發現有換行符時則認為該行已經結束。
在我們寫Java程序時,大多數都認為\r\n為一個文本的一行結束,但這個換行符根據當前系統的不同,換行符也不相同,比如在Linux/Unix下換行符是\n,而在Windows下則是\r\n。如果將換行符定為\r\n,在讀取由Linux系統生成的文本文件則會出現亂碼。
3.讀取正常,但中間偶爾會出現亂碼
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);
// 把文件當字符串處理,直接打印做為一個例子。
System.out.print(new String(bs, 0, size));
byteBuf.clear();
}
}這是網上大多數使用NIO來讀取大文件的例子,但這有個問題。中文字符根據編碼不同,會占用2到3個字節,而上面程序中每次都讀取1024個字節,那這樣就會出現一個問題,如果該文件中第1023,1024,1025三個字節是一個漢字,那么一次讀1024個字節就會將這個漢字切分成兩瓣,生成String對象時就會出現亂碼。
解決思路是判斷這讀取的1024個字節,最后一位是不是\n,如果不是,那么將最后一個\n以后的byte[]緩存起來,加到下一次讀取的byte[]頭部。
以下為代碼結構:

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 {
// 每次讀取文件內容緩沖大小,默認為1024個字節
private int bufSize = 1024;
// 換行符
private byte key = "\n".getBytes()[0];
// 當前行數
private long lineNum = 0;
// 文件編碼,默認為gb2312
private String encode = "gb2312";
// 具體業務邏輯監聽器
private ReaderListener readerListener;
/**
* 設置回調方法
* @param readerListener
*/
public NIOFileReader(ReaderListener readerListener) {
this.readerListener = readerListener;
}
/**
* 設置回調方法,并指明文件編碼
* @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);
// 每次讀取的內容
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;
// 如果發現有上次未讀完的緩存,則將它加到當前讀取的內容前面
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;
// 每次讀一行內容,以 key(默認為\n) 作為結束符
while ((endIndex = indexOf(newStrByte, fromIndex)) != -1) {
byte[] bLine = substring(newStrByte, fromIndex, endIndex);
line = new String(bLine, 0, bLine.length, encode);
lineNum++;
// 輸出一行內容,處理方式由調用方提供
readerListener.outLine(line.trim(), lineNum, false);
fromIndex = endIndex + 1;
}
// 將未讀取完成的內容放到緩存中
tempBs = substring(newStrByte, fromIndex, newStrByte.length);
}
// 將剩下的最后內容作為一行,輸出,并指明這是最后一行
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[]直到指定結束位置為止生成一個全新的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逐行讀數據回調方法
*/
public abstract class ReaderListener {
// 一次讀取行數,默認為500
private int readColNum = 500;
private List<String> list = new ArrayList<String>();
/**
* 設置一次讀取行數
* @param readColNum
*/
protected void setReadColNum(int readColNum) {
this.readColNum = readColNum;
}
/**
* 每讀取到一行數據,添加到緩存中
* @param lineStr 讀取到的數據
* @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(具體業務邏輯)
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);
}
}感謝各位的閱讀!關于“java讀取超大文件的示例”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
網頁名稱:java讀取超大文件的示例
鏈接地址:http://www.yijiale78.com/article12/gcesdc.html
成都網站建設公司_創新互聯,為您提供定制網站、服務器托管、品牌網站建設、營銷型網站建設、用戶體驗、云服務器
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯