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


当前回答

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

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

其他回答

要避免try catch,请使用:

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

迂腐的答案(虽然不一定是最有用的答案,这取决于你想对结果做什么)是:

string.length() * 2

Java字符串物理存储在UTF-16BE编码中,每个代码单元使用2个字节,而String.length()以UTF-16代码单元测量长度,因此这相当于:

final byte[] utf16Bytes= string.getBytes("UTF-16BE");
System.out.println(utf16Bytes.length);

这将告诉你内部char数组的大小,单位是字节。

注意:“UTF-16”将给出与“UTF-16BE”不同的结果,因为前者编码将插入一个BOM,将数组长度增加2个字节。

有一个叫做getBytes()的方法。明智地使用它。

试试这个:

Bytes.toBytes(x).length

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

尝试使用apache commons:

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