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;
}
}
}