Completely solve the problem of Chinese Characters in

Source: Internet
Author: User

Completely solve the problem of Chinese Characters in

Author: Chen yuefeng

From: http://blog.csdn.net/mailbomb

 

During the design of the program, Chinese characters may occur when the record set is stored, data is transmitted over the network, and data in the resource file is read.

The essence of Chinese problems is that the character encoding used for saving and transmitting Chinese characters is different from the character encoding used for reading and obtaining Chinese characters. All the phones in j2s support character set in UTF-8 format.

When data is used, the problem of Chinese characters is usually generated when the string and byte array are converted. The following is a conversion method for encoding Chinese characters to produce garbled characters:

 

Import java. Io .*;

Public class test {

/**

* Convert a byte array to a string

* @ Param bytes the byte array to be converted

* @ Return refers to the converted string.

*/

Public static string byte2string (byte [] bytes ){

Try {

Bytearrayinputstream BAIS = new bytearrayinputstream (bytes );

Datainputstream Dis = new datainputstream (BAIS );

String S = dis. readutf ();

// Close the stream

Dis. Close ();

BAIS. Close ();

Return S;

} Catch (exception e ){

Return NULL;

}

}

/**

* Convert a string to a byte array

* @ Param s the string to be converted

* @ Return the byte array generated after conversion

*/

Public static byte [] string2byte (string s ){

Try {

Bytearrayoutputstream baos = new bytearrayoutputstream ();

Dataoutputstream Bos = new dataoutputstream (baos );

Bos. writeutf (s );

Byte [] bytes = baos. tobytearray ();

// Close the stream

Bos. Close ();

Baos. Close ();

Return bytes;

} Catch (exception e ){

Return NULL;

}

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.