java读取_Java读取文件加速

在执行IO时,Java的InputStream被广泛使用,比如DataInputStream.readInt等等。事实上,这些高度封装的接口奇慢无比。我有一个项目启动时需要读取90MB左右的词典文件,用DataInputStream耗时3秒以上,换用java.nio包直接操作内存字节,可以加速到300ms左右,整整提速10倍!当然,前提是你熟悉位运算。

java.nio中提供了两个类 FileChannel 和 ByteBuffer来将文件映射到内存,其中FileChannel表示文件通道,ByteBuffer是一个缓冲区。

具体步骤

①从FileInputStream、FileOutputStream以及RandomAccessFile对象获取文件通道

②将文件内存映射到ByteBuffer

③通过byteBuffer.array()接口得到一个byte数组

④直接操作字节

示例代码FileInputStream fis = new FileInputStream(path);

// 1.从FileInputStream对象获取文件通道FileChannel

FileChannel channel = fis.getChannel();

int fileSize = (int) channel.size();

// 2.从通道读取文件内容

ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);

// channel.read(ByteBuffer) 方法就类似于 inputstream.read(byte)

// 每次read都将读取 allocate 个字节到ByteBuffer

channel.read(byteBuffer);

// 注意先调用flip方法反转Buffer,再从Buffer读取数据

byteBuffer.flip();

// 可以将当前Buffer包含的字节数组全部读取出来

byte[] bytes = byteBuffer.array();

byteBuffer.clear();

// 关闭通道和文件流

channel.close();

fis.close();

int index = 0;

size = Utility.bytesHighFirstToInt(bytes, index);

index += 4;

其中,如果你当初使用了DataOutputStream.writeInt来保存文件的话,那么在读取的时候就要注意了。writeInt写入四个字节,其中高位在前,低位在后,所以将byte数组转为int的时候需要倒过来转换:/**

* 字节数组和整型的转换,高位在前,适用于读取writeInt的数据

*

* @param bytes 字节数组

* @return 整型

*/

public static int bytesHighFirstToInt(byte[] bytes, int start){

int num = bytes[start + 3] & 0xFF;

num |= ((bytes[start + 2] <

num |= ((bytes[start + 1] <

num |= ((bytes[start] <

return num;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值