Java string encoding and conversion

Source: Internet
Author: User

Http://wenwen.soso.com/z/q191078042.htm

 

String newstr = new string (oldstr. getbytes (), "UTF-8 ");

The string class in Java is encoded according to Unicode. When string (byte [] bytes, string encoding) is used to construct a string, encoding refers to the encoding method of the data in bytes, rather than the encoding method of the final string. In other words, enables the system to convert bytes data from encoding to unicode encoding. If this parameter is not specified, JDK determines the bytes encoding method based on the operating system.

When we read data from a file, it is best to use the inputstream method, and then use string (byte [] bytes, string encoding) to specify the file encoding method. Do not use reader because reader automatically converts the file content to unicode encoding Based on the encoding method specified by JDK.

When we read text data from the database, we use the resultset. getbytes () method to obtain the byte array. We can also use the encoded string construction method.

Resultset RS;
Bytep [] bytes = Rs. getbytes ();
String STR = new string (bytes, "gb2312 ");

Do not take the following steps.

Resultset RS;
String STR = Rs. getstring ();
STR = new string (Str. getbytes ("iso8859-1"), "gb2312 ");

The efficiency of this encoding conversion method is low. The reason for doing so is that when the resultset is executed by the getstring () method, the data encoding method in the database is iso8859-1 by default. The system converts the data to Unicode according to the encoding method of the iso8859-1. Use Str. getbytes ("iso8859-1") to restore the data, and then use new string (bytes, "gb2312") to convert the data from gb2312 to Unicode, there are many steps in the middle.

When reading parameters from httprequest, you can use the reqeust. setcharacterencoding () method to set the encoding method. The read content is correct.
Turn: http://www.blogjava.net/rabbit/archive/2008/03/27/189009.html

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.