java如何读取超大文件

作者:Okey 时间:2022-10-24 08:20:54 

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[]头部。

以下为代码结构:

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 {

// 每次读取文件内容缓冲大小,默认为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);
}
}

来源:https://blog.csdn.net/hbyscl/article/details/22717063

标签:java,读取文件
0
投稿

猜你喜欢

  • c#多线程之间的排他锁的实现

    2022-06-11 12:31:53
  • 全面了解Java中Native关键字的作用

    2022-07-13 02:01:09
  • 使用Java和WebSocket实现网页聊天室实例代码

    2023-11-26 00:16:02
  • Java利用自定义注解、反射实现简单BaseDao实例

    2022-09-06 05:29:30
  • Spring Boot2.X国际化文件编写配置

    2023-02-24 11:34:24
  • Session过期后自动跳转到登录页面的实例代码

    2022-01-30 13:48:56
  • Android仿一点资讯收藏Toast动画效果

    2022-01-15 18:42:33
  • Android编程实现将压缩数据库文件拷贝到安装目录的方法

    2022-06-18 16:06:56
  • Android WaveView实现水流波动效果

    2021-11-09 16:50:59
  • 命令行编译java文件方式

    2023-01-18 18:35:47
  • Android 自定义对话框 showSetPwdDialog

    2022-04-25 22:55:00
  • Android自定义View仿探探卡片滑动效果

    2023-03-18 14:54:16
  • Unity实现枚举类型中文显示

    2023-02-22 12:00:28
  • C# 9.0新特性——只初始化设置器

    2023-03-19 02:31:45
  • Android开发Compose集成高德地图实例

    2022-09-05 01:44:28
  • java实现图片反色处理示例

    2022-07-09 20:53:34
  • Android Shader应用开发之霓虹闪烁文字效果

    2022-09-11 16:43:20
  • iOS应用中使用Toolbar工具栏方式切换视图的方法详解

    2023-06-21 09:24:48
  • SpringBoot通过自定义注解实现参数校验

    2023-09-21 21:11:02
  • maven为MANIFEST.MF文件添加内容的方法

    2022-10-29 11:15:56
  • asp之家 软件编程 m.aspxhome.com