java讀取超大文件的示例

這篇文章給大家分享的是有關(guān)java讀取超大文件的示例的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

成都創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于網(wǎng)站制作、成都網(wǎng)站建設(shè)、沂源網(wǎng)絡(luò)推廣、小程序制作、沂源網(wǎng)絡(luò)營銷、沂源企業(yè)策劃、沂源品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;成都創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供沂源建站搭建服務(wù),24小時服務(wù)熱線:13518219792,官方網(wǎng)址:muchs.cn

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):

java讀取超大文件的示例

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);
 }
}

感謝各位的閱讀!關(guān)于“java讀取超大文件的示例”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

網(wǎng)頁名稱:java讀取超大文件的示例
鏈接地址:http://muchs.cn/article12/gcesdc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、服務(wù)器托管品牌網(wǎng)站建設(shè)、營銷型網(wǎng)站建設(shè)、用戶體驗、云服務(wù)器

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司