Encode String to UTF-8

后端 未结 11 1893
忘掉有多难
忘掉有多难 2020-11-22 08:33

I have a String with a \"ñ\" character and I have some problems with it. I need to encode this String to UTF-8 encoding. I have tried it by this way, but it doesn\'t work:

11条回答
  •  一整个雨季
    2020-11-22 09:19

    In a moment I went through this problem and managed to solve it in the following way

    first i need to import

    import java.nio.charset.Charset;
    

    Then i had to declare a constant to use UTF-8 and ISO-8859-1

    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private static final Charset ISO = Charset.forName("ISO-8859-1");
    

    Then I could use it in the following way:

    String textwithaccent="Thís ís a text with accent";
    String textwithletter="Ñandú";
    
    text1 = new String(textwithaccent.getBytes(ISO), UTF_8);
    text2 = new String(textwithletter.getBytes(ISO),UTF_8);
    

提交回复
热议问题