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

前端 未结 5 757
旧巷少年郎
旧巷少年郎 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:36

    You need to know the encoding - otherwise it's a meaningless question. For example, "foo" is 6 bytes in UTF-16, but 3 bytes in ASCII. Assuming you're reading a line at a time (given your question) you should know which encoding you're using as you should have specified it when you started to read.

    You can call String.getBytes(charset) to get the encoded representation of a particular string.

    Do not just call String.getBytes() as that will use the platform default encoding.

    Note that all of this is somewhat make-work... you've read the bytes, decoded them to text, then you're re-encoding them into bytes...

提交回复
热议问题