gpt4 book ai didi

java - RandomAccessFile.read() 返回的值大于读取到字符串中的字符数

转载 作者:行者123 更新时间:2023-12-02 00:23:15 24 4
gpt4 key购买 nike

我有一个 RandomAccessFile raFile,我从中以固定大小的 block 将数据读入缓冲区:

byte[] fileBuffer = new byte[BUFFER_SIZE];

while((readBytes = raFile.read(fileBuffer) >= 0) {
String bufferStr = new String(fileBuffer, 0, readBytes);
String testerStr = new String(fileBuffer);

System.out.println(readBytes+","+bufferStr.length()+","+testerStr.length());
}

我所期望的是 raFile.read() 读取与 BUFFER_SIZE 一样多的字节(文件末尾除外),并且读取相同的值被复制到readBytes。虽然这基本上是正确的,但有时,对于 4096 的 BUFFER_SIZE,我会得到以下输出:

readBytes bufferStr testerStr
4096            4092              4092
4096            4090              4090
4096            4094              4094
4096             4095              4095

如果正在读取 4096 字节,为什么即使不在文件末尾,bufferStrtesterStr 的长度也小于该值?

引用:This表示 read() 返回读入缓冲区的字节总数。

最佳答案

因为有些字符需要多个字节。 buffer String.length() 给出的是字符数,而不是字节数。

关于java - RandomAccessFile.read() 返回的值大于读取到字符串中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10550843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com