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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.