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


当前回答

要避免try catch,请使用:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.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)

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

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

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

字符串是一个字符列表(即代码点)。用于表示字符串的字节数完全取决于使用哪种编码将其转换为字节。

也就是说,你可以把字符串转换成字节数组,然后查看它的大小,如下所示:

// The input string for this test
final String string = "Hello World";

// Check length, in characters
System.out.println(string.length()); // prints "11"

// Check encoded sizes
final byte[] utf8Bytes = string.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "11"

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

final byte[] utf32Bytes = string.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "44"

final byte[] isoBytes = string.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "11"

final byte[] winBytes = string.getBytes("CP1252");
System.out.println(winBytes.length); // prints "11"

因此,您可以看到,即使是一个简单的“ASCII”字符串也可以在其表示中具有不同的字节数,这取决于使用的编码。使用您感兴趣的字符集作为getBytes()的参数。不要陷入假设UTF-8将每个字符表示为一个字节的陷阱,因为这也不是真的:

final String interesting = "\uF93D\uF936\uF949\uF942"; // Chinese ideograms

// Check length, in characters
System.out.println(interesting.length()); // prints "4"

// Check encoded sizes
final byte[] utf8Bytes = interesting.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "12"

final byte[] utf16Bytes= interesting.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "10"

final byte[] utf32Bytes = interesting.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "16"

final byte[] isoBytes = interesting.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "4" (probably encoded "????")

final byte[] winBytes = interesting.getBytes("CP1252");
System.out.println(winBytes.length); // prints "4" (probably encoded "????")

(注意,如果不提供字符集参数,则使用平台的默认字符集。这在某些情况下可能是有用的,但一般情况下,你应该避免依赖默认值,当需要编码/解码时总是使用显式字符集。)

试试这个:

Bytes.toBytes(x).length

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