java - 如何正确读取字节java文件
问题描述
我想用 UTF-8 快速逐行读取大 csv 文件(大约 1gb)。我为它创建了一个类,但它不能正常工作。UTF-8 从 2 个字节解码西里尔符号。我使用字节缓冲区来读取它,例如它有 10 个字节的长度。因此,如果符号由文件中的 10 和 11 个字节组成,它将无法正常解码:(
public class MyReader extends InputStream {
private FileChannel channel;
private ByteBuffer buffer = ByteBuffer.allocate(10);
private int buffSize = 0;
private int position = 0;
private boolean EOF = false;
private CharBuffer charBuffer;
private MyReader() {}
static MyReader getFromFile(final String path) throws IOException {
MyReader myReader = new MyReader();
myReader.channel = FileChannel.open(Path.of(path),
StandardOpenOption.READ);
myReader.initNewBuffer();
return myReader;
}
private void initNewBuffer() {
try {
buffSize = channel.read(buffer);
buffer.position(0);
charBuffer = Charset.forName("UTF-8").decode(buffer);
buffer.position(0);
} catch (IOException e) {
throw new RuntimeException("Error reading file: {}", e);
}
}
@Override
public int read() throws IOException {
if (EOF) {
return -1;
}
if (position < charBuffer.length()) {
return charBuffer.array()[position++];
} else {
initNewBuffer();
if (buffSize < 1) {
EOF = true;
} else {
position = 0;
}
return read();
}
}
public char[] readLine() throws IOException {
int readResult = 0;
int startPos = position;
while (readResult != -1) {
readResult = read();
}
return Arrays.copyOfRange(charBuffer.array(), startPos, position);
}
}
解决方案
糟糕的解决方案,但它有效)
private void initNewBuffer() {
try {
buffSize = channel.read(buffer);
buffer.position(0);
charBuffer = StandardCharsets.UTF_8.decode(buffer);
if (buffSize > 0) {
byte edgeByte = buffer.array()[buffSize - 1];
if (edgeByte == (byte) 0xd0 ||
edgeByte == (byte) 0xd1 ||
edgeByte == (byte) 0xc2 ||
edgeByte == (byte) 0xd2 ||
edgeByte == (byte) 0xd3
) {
channel.position(channel.position() - 1);
charBuffer.limit(charBuffer.limit()-1);
}
}
buffer.position(0);
} catch (IOException e) {
throw new RuntimeException("Error reading file: {}", e);
}
}
推荐阅读
- java - Android Studio OpenCV 中的颜色检测
- javascript - 使用 Javascript 传递选定的复选框值
- regex - 正则表达式查找相同字符的多次出现并排除行中的单词
- c - 如何使用 OpenMP 在其他 for 循环中并行化 for 循环
- java - FFmpegFrameGrabber 仅使用关键帧更快的 SetTimestamp
- r - 如何为自定义 S3 类实现提取/子集([、[<-、[[、[[<-)] 函数?
- wordpress - 如何在我的 codeigniter 控制器中从 wordpress DB 获取最近的帖子?
- r - 如何计算向量中的重复条目?
- extjs - Sencha 6.5.2(现代)带小数分隔符的数字字段
- cassandra - Nosql之类的bigtable是如何存储Image数据的?