Home >Java >JavaBase >Introduction to solving string garbled characters in Java

Introduction to solving string garbled characters in Java

尚
Original
2019-12-02 11:10:373055browse

Introduction to solving string garbled characters in Java

java string garbled solution: (Recommended: java video tutorial)

System.out.println(str);
            String str1 = new String(str.getBytes("ISO-8859-1"), "utf-8");
            System.out.println(str1);
            String str2 = new String(str.getBytes("gb2312"), "utf-8");
            System.out.println(str2);
            String str3 = new String(str.getBytes("gbk"), "utf-8");
            System.out.println(str3);

str.getBytes(charsetName);charsetName is the original character Encoding

"utf-8" is to convert str to utf-8 encoding.

new String(str.getBytes("gbk"),"iso8859-1")

Step one: byte[] bytes=str.getBytes("gbk")

Tell the java virtual machine to convert Chinese into a byte array in the "gbk" method. One Chinese character corresponds to two bytes.

The corresponding second step is:

When String s=new String(bytes, "iso8859-1"), each byte is assembled into a "?" . At this time, s is several "?". We can regard "?" as a special Chinese character, and the information it represents can be restored without loss.

java.lang.String.getBytes(String charsetName) method encodes this String into a byte sequence using the specified character set and stores the result into a new byte array.

Declaration

The following is the declaration of the java.lang.String.getBytes() method

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

Parameters: charset -- This is the name of a supported character set.

Return value: This method returns the resulting byte array.

new String(byte[],decode) method

Compared with getBytes, you can restore the "中" character through new String(byte[], decode),

This new String(byte[],decode) actually uses the specified encoding decode to parse byte[] into a string.

Exception: UnsupportedEncodingException -- If the specified character set is not supported.

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of Introduction to solving string garbled characters in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn