在Java中,如果我有一个字符串x,我如何计算该字符串中的字节数?


当前回答

根据如何在Java中转换字符串和UTF8字节数组:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");
System.out.println(b.length);

其他回答

尝试使用apache commons:

String src = "Hello"; //This will work with any serialisable object
System.out.println(
            "Object Size:" + SerializationUtils.serialize((Serializable) src).length)

如果你运行64位引用:

sizeof(string) = 
8 + // object header used by the VM
8 + // 64-bit reference to char array (value)
8 + string.length() * 2 + // character array itself (object header + 16-bit chars)
4 + // offset integer
4 + // count integer
4 + // cached hash code

换句话说:

sizeof(string) = 36 + string.length() * 2

对于32位虚拟机或64位虚拟机,如果有压缩OOPs (-XX:+UseCompressedOops),则引用为4字节。所以总数是:

sizeof(string) = 32 + string.length() * 2

这没有考虑到对字符串对象的引用。

根据如何在Java中转换字符串和UTF8字节数组:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");
System.out.println(b.length);

试试这个:

Bytes.toBytes(x).length

假设你之前声明并初始化了x

要避免try catch,请使用:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
System.out.println(b.length);