Encode String to UTF-8

后端 未结 11 1809
忘掉有多难
忘掉有多难 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:04

    How about using

    ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(myString)
    
    0 讨论(0)
  • 2020-11-22 09:06

    String objects in Java use the UTF-16 encoding that can't be modified.

    The only thing that can have a different encoding is a byte[]. So if you need UTF-8 data, then you need a byte[]. If you have a String that contains unexpected data, then the problem is at some earlier place that incorrectly converted some binary data to a String (i.e. it was using the wrong encoding).

    0 讨论(0)
  • 2020-11-22 09:06
    String value = new String(myString.getBytes("UTF-8"));
    

    and, if you want to read from text file with "ISO-8859-1" encoded:

    String line;
    String f = "C:\\MyPath\\MyFile.txt";
    try {
        BufferedReader br = Files.newBufferedReader(Paths.get(f), Charset.forName("ISO-8859-1"));
        while ((line = br.readLine()) != null) {
            System.out.println(new String(line.getBytes("UTF-8")));
        }
    } catch (IOException ex) {
        //...
    }
    
    0 讨论(0)
  • 2020-11-22 09:09

    Use byte[] ptext = String.getBytes("UTF-8"); instead of getBytes(). getBytes() uses so-called "default encoding", which may not be UTF-8.

    0 讨论(0)
  • 2020-11-22 09:11

    This solved my problem

        String inputText = "some text with escaped chars"
        InputStream is = new ByteArrayInputStream(inputText.getBytes("UTF-8"));
    
    0 讨论(0)
  • 2020-11-22 09:13

    You can try this way.

    byte ptext[] = myString.getBytes("ISO-8859-1"); 
    String value = new String(ptext, "UTF-8"); 
    
    0 讨论(0)
提交回复
热议问题