【发布时间】:2021-04-05 17:56:04
【问题描述】:
我有这段代码旨在将字符串拆分为字符串数组,使用 CHUNK_SIZE 作为拆分的大小,以字节为单位(我这样做是为了对结果进行分页)。 这在大多数情况下适用于字符为 1 字节的情况,但是当我在拆分位置有一个多字节字符(例如 2 字节法语字符(如 é)或 4 字节中文字符)时,我最终得到在我的第一个数组元素的末尾和第二个数组元素的开头有 2 个不可读的字符。
有没有办法修复代码以考虑多字节字符,以便在最终结果中维护它们?
public static ArrayList<String> splitFile(String data) throws Exception {
ArrayList<String> messages = new ArrayList<>();
int CHUNK_SIZE = 400000;// 0.75mb
if (data.getBytes().length > CHUNK_SIZE) {
byte[] buffer = new byte[CHUNK_SIZE];
int start = 0, end = buffer.length;
long remaining = data.getBytes().length;
ByteArrayInputStream inputStream =
new ByteArrayInputStream(data.getBytes());
while ((inputStream.read(buffer, start, end)) != -1) {
ByteArrayOutputStream outputStream =
new ByteArrayOutputStream();
outputStream.write(buffer, start, end);
messages.add(outputStream.toString("UTF-8"));
remaining = remaining - end;
if (remaining <= end) {
end = (int) remaining;
}
}
return messages;
}
messages.add(data);
return messages;
}
【问题讨论】:
标签: java string split character non-ascii-characters