java nio 从内存读信息,Java nio:如何从内存映射文件用正确的字符集读取字符

for a new project, I have to read the characters of a file (with configurable encoding) to handle the input. As some of these files can be quite large (> 100MB), I wanted to check out the Java nio's ability to memory map files for faster access.

However, I was not able to figure out, how I am able to create something "Reader"-like to read from the MappedByteBuffer with the correct charset decoding.

To create the MappedByteBuffer, I currently use:

RandomAccessFile raFile = new RandomAccessFile("myFile.bla", "r");

FileChannel channel = raFile.getChannel();

MappedByteBuffer mappedByteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size());

I know, that I can use getChar() to get a character from the MappedByteBuffer, but how is it possible to specify the encoding? In the javadoc it states, that always two bytes are read and combined to one char, but what is with ASCII encoded files?

I also found the Channels.newReader(...) methods, which however can only handle the channel, not the memory mapped file. Is there something similar for the MappedByteBuffer?

Just to make sure: I know that memory mapping is a somewhat expensive operation and therefore only useful for larger files. I made no decision (yet), whether to use it or not, but want to evaluate it for my special use case.

Many thanks in advance + best regards,

Andreas

解决方案

You can use a CharsetDecoder retrieved from your favorite Charset with Charset#newDecoder().

StandardCharsets.UTF_8.newDecoder().decode(mappedByteBuffer)

This returns a CharBuffer from which you can get char values.

Note that this does consume the full MappedByteBuffer. If you only want a few bytes, construct a new ByteBuffer from the few bytes of the original MappedByteBuffer and decode that.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值