我有一种情况需要知道 String
/encoding 对的大小(以字节为单位),但不能使用 getBytes()
方法,因为 1) String
非常大,在 byte[]
数组中复制 String
会使用大量内存,但更重要的是 2) getBytes()
根据 String
的长度 * 每个字符的最大可能字节数分配一个 byte[]
数组。因此,如果我有一个包含 1.5B 个字符和 UTF-16 编码的 String
,getBytes()
将尝试分配一个 3GB 的数组并失败,因为数组被限制为 2^ 32 - X 字节(X 是特定于 Java 版本的)。
那么 - 有什么方法可以直接从 String
对象计算 String
/encoding 对的字节大小吗?
更新:
这是 jtahlborn 的回答的有效实现:
private class CountingOutputStream extends OutputStream {
int total;
@Override
public void write(int i) {
throw new RuntimeException("don't use");
}
@Override
public void write(byte[] b) {
total += b.length;
}
@Override public void write(byte[] b, int offset, int len) {
total += len;
}
}
最佳答案
很简单,只需将其写入一个虚拟输出流即可:
class CountingOutputStream extends OutputStream {
private int _total;
@Override public void write(int b) {
++_total;
}
@Override public void write(byte[] b) {
_total += b.length;
}
@Override public void write(byte[] b, int offset, int len) {
_total += len;
}
public int getTotalSize(){
_total;
}
}
CountingOutputStream cos = new CountingOutputStream();
Writer writer = new OutputStreamWriter(cos, "my_encoding");
//writer.write(myString);
// UPDATE: OutputStreamWriter does a simple copy of the _entire_ input string, to avoid that use:
for(int i = 0; i < myString.length(); i+=8096) {
int end = Math.min(myString.length(), i+8096);
writer.write(myString, i, end - i);
}
writer.flush();
System.out.println("Total bytes: " + cos.getTotalSize());
它不仅简单,而且可能与其他“复杂”答案一样快。
关于java - 在不转换为 byte[] 的情况下获取带字节编码的 String 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19852460/