Java String type encoding conversion __string

Source: Internet
Author: User
String newstr = new String (Oldstr.getbytes (), "UTF-8");

The string class in Java is encoded in Unicode, and when a string is constructed using string (byte[] bytes, string encoding), encoding refers to that the data in the bytes is encoded in that way, Rather than what the last string is encoded, in other words, the system converts the data in bytes from encoding encoding to Unicode encoding. If not indicated, the bytes encoding will be determined by the JDK according to 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 indicate how the file is encoded. Do not use the reader method, because the reader method automatically converts the contents of the file into Unicode encoding according to the code specified by the JDK.

When we read the text data from the database, we use the Resultset.getbytes () method to get the byte array, and also adopt the string construction method with the encoding way.

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");

This method of encoding conversion is efficient. The reason for this is that resultset the data encoding in the default database is iso8859-1 when the GetString () method executes. The system converts the data to Unicode according to the iso8859-1 encoding. Using Str.getbytes ("iso8859-1") to restore data, and then using the new String (bytes, "gb2312") to convert data from gb2312 to Unicode, there are many steps in the middle.

When you read the parameters from the HttpRequest, you use the Reqeust.setcharacterencoding () method to set the encoding, and the content read is correct.
Ext: 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.