Is there any way to get the size in bytes of a string in Java?

前端 未结 5 755
旧巷少年郎
旧巷少年郎 2021-01-21 19:20

I need the size in bytes of each line in a file, so I can get a percentage of the file read. I already got the size of the file with file.length(), but how do I get

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 19:59

    Consider you have a string variable called hello_str

    final String hello_str = "Hello World";
    
     //Check Character length
     hello_str.length() //output will be 11
     // Check encoded sizes
     final byte[] utf8Bytes = hello_str.getBytes("UTF-8");
     utf8Bytes.length  //output will be 11
    
     final byte[] utf16Bytes= hello_str.getBytes("UTF-16");
     utf16Bytes.length // output will be "24"
    
      final byte[] utf32Bytes = hello_str.getBytes("UTF-32");
      utf32Bytes.length // output will be "44"
    

提交回复
热议问题