在Java中,如果我有一个字符串x,我如何计算该字符串中的字节数?
当前回答
尝试使用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);
迂腐的答案(虽然不一定是最有用的答案,这取决于你想对结果做什么)是:
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个字节。
试试这个:
Bytes.toBytes(x).length
假设你之前声明并初始化了x
String实例在内存中分配一定数量的字节。也许您正在查看类似sizeof(“Hello World”)的东西,它将返回数据结构本身分配的字节数。
In Java, there's usually no need for a sizeof function, because we never allocate memory to store a data structure. We can have a look at the String.java file for a rough estimation, and we see some 'int', some references and a char[]. The Java language specification defines, that a char ranges from 0 to 65535, so two bytes are sufficient to keep a single char in memory. But a JVM does not have to store one char in 2 bytes, it only has to guarantee, that the implementation of char can hold values of the defines range.
sizeof在Java中没有任何意义。但是,假设我们有一个大的String并且一个char分配两个字节,那么String对象的内存占用至少是2 * str.length()字节。
尝试使用apache commons:
String src = "Hello"; //This will work with any serialisable object
System.out.println(
"Object Size:" + SerializationUtils.serialize((Serializable) src).length)
推荐文章
- 如何配置slf4j-simple
- Printf与std::字符串?
- 在Jar文件中运行类
- 带参数的可运行?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- 如何在PHP中截断字符串最接近于一定数量的字符?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap