以字节为单位获取String w/encoding的大小而不转换为byte []

elh*_*efe 17 java string size byte

我有一种情况,我需要知道一个String/编码对的大小,以字节为单位,但不能使用该getBytes()方法,因为1)String非常大并且复制String在一个byte[]数组中将使用大量的内存,但更多的是第2点)根据*每个字符的最大可能字节长度getBytes()分配一个byte[]数组String.因此,如果我有String1.5B字符和UTF-16编码,getBytes()将尝试分配3GB数组并失败,因为数组限制为2 ^ 32 - X字节(X是特定于Java版本).

那么 - 有没有办法String直接从String对象计算/编码对的字节大小?

更新:

这是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;
    }
}
Run Code Online (Sandbox Code Playgroud)

jta*_*orn 11

很简单,只需将其写入虚拟输出流:

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());
Run Code Online (Sandbox Code Playgroud)

它不仅简单,而且可能与其他"复杂"答案一样快.

  • @AminSuzani - 将 `_total` 更改为 `long` 就足够了。 (2认同)