Java String.getBytes( charsetName ) vs String.getBytes ( Charset object )

后端 未结 4 2075
后悔当初
后悔当初 2020-12-15 18:00

I need to encode a String to byte array using UTF-8 encoding. I am using Google guava, it has Charsets class already define Charset instance for UTF-8 encoding. I have 2 way

4条回答
  •  悲&欢浪女
    2020-12-15 18:59

    Since they return the same result, you should use method 2 because it generally safer and more efficient to avoid asking the library to parse and possibly break on a user-supplied string. Also, avoiding the try-catch will make your own code cleaner as well.

    The Charsets.UTF_8 can be more easily checked at compile-time, which is most likely the reason you do not need a try-catch.

提交回复
热议问题