Home Java javaTutorial Example code summary of three methods to implement java character transcoding

Example code summary of three methods to implement java character transcoding

Mar 31, 2017 am 10:47 AM

This article mainly introduces the summary of the three methods of java character transcoding and related information with examples. Friends in need can refer to the following

java character transcoding: three methods

Prerequisite for successful transcoding: no garbled characters after decoding

Transcoding process: File (gbk)-->Decoding--> ;Encoding--->File (utf-8)

Note: If you have any questions, please leave a message

Specific examples below

Method one: Java.lang.String

//用于解码的构造器: 
String(byte[] bytes, int offset, int length, String charsetName)  
String(byte[] bytes, String charsetName)  
 
用于编码的方法: 
byte[] getBytes(String charsetName) //使用指定字符集进行编码 
 byte[] getBytes() //使用系统默认字符集进行编码
Copy after login
public void convertionString() throws UnsupportedEncodingException{ 
    String s = "清山"; 
    byte[] b = s.getBytes("gbk");//编码 
    String sa = new String(b, "gbk");//解码:用什么字符集编码就用什么字符集解码 
    System.out.println(sa); 
     
    b = sa.getBytes("utf-8");//编码 
    sa = new String(b, "utf-8");//解码 
    System.err.println(sa); 
  }
Copy after login

Method two: java.io.InputStreamReader/OutputStreamWriter :Bridge conversion

package com.qingshan.io; 
 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.io.UnsupportedEncodingException; 
 
/** 
 * <pre class="brush:php;toolbar:false"> 
 * 使用java.io桥转换:对文件进行转码 
 * 
*
* 2012 Qingshan Group 版权所有 *
* @author thetopofqingshan * @version 1.0.0 * @since JDK 1.5 * @date 2012-4-28 */ public class CharsetConvertion { private FileInputStream fis;// 文件输入流:读取文件中内容 private InputStream is; private InputStreamReader isr; private OutputStream os; private OutputStreamWriter osw;//写入 private char[] ch = new char[1024]; public void convertionFile() throws IOException{ is = new FileInputStream("C:/项目进度跟踪.txt");//文件读取 isr = new InputStreamReader(is, "gbk");//解码 os = new FileOutputStream("C:/项目进度跟踪_utf-8.txt");//文件输出 osw = new OutputStreamWriter(os, "utf-8");//开始编码 char[] c = new char[1024];//缓冲 int length = 0; while(true){ length = isr.read(c); if(length == -1){ break; } System.out.println(new String(c, 0, length)); osw.write(c, 0, length); osw.flush(); } } public void convertionString() throws UnsupportedEncodingException{ String s = "清山集团"; byte[] b = s.getBytes("gbk");//编码 String sa = new String(b, "gbk");//解码:用什么字符集编码就用什么字符集解码 System.out.println(sa); b = sa.getBytes("utf-8");//编码 sa = new String(b, "utf-8");//解码 System.err.println(sa); } /** *
 
   * 关闭所有流 
   * 
* */ public void close(){ if(isr != null){ try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } if(is != null){ try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(osw != null){ try { osw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(os != null){ try { os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** *
 
   * 用io读取文件内容 
   * 
* * @throws IOException * 读取过程中发生错误 * */ /** *
 
   * 
   * 
* @param path * @param charset * @throws IOException * */ public void read(String path, String charset) throws IOException { fis = new FileInputStream(path); isr = new InputStreamReader(fis, charset); while (fis.available() > 0) { int length = isr.read(ch); System.out.println(new String(ch)); } } public static void main(String[] args) { try { CharsetConvertion cc = new CharsetConvertion(); cc.convertionFile(); cc.convertionString(); cc.close(); } catch (IOException e) { e.printStackTrace(); } } }
Copy after login

Method 3:java.nio.Charset

package com.qingshan.nio; 
 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.nio.ByteBuffer; 
import java.nio.CharBuffer; 
import java.nio.channels.FileChannel; 
import java.nio.charset.Charset; 
import java.nio.charset.CharsetDecoder; 
import java.nio.charset.CharsetEncoder; 
 
/** 
 * <pre class="brush:php;toolbar:false"> 
 * 使用nio中的Charset转换字符:整个流程是文件读取-->byte-->解码(正确)-->编码--->byte-->写入文件 
 * 
*
* * 2012 Qingshan Group 版权所有 *
* * * @author thetopofqingshan * @version 1.0.0 * @since JDK 1.5 * @date 2012-4-27 */ public class CharsetConvertion { private FileInputStream fis;// 文件输入流:读取文件中内容 private FileChannel in;// 文件通道:双向,流从中而过 private FileChannel out;// 文件通道:双向,流从中而过 private FileOutputStream fos;// 文件输出流:向文件中写入内容 private ByteBuffer b = ByteBuffer.allocate(1024 * 3);// 设置缓存区的大小 private Charset inSet;// 解码字符集 private Charset outSet;// 编码字符集 private CharsetDecoder de;// 解码器 private CharsetEncoder en;// 编码器 private CharBuffer convertion;// 中间的字符数据 private ByteBuffer temp = ByteBuffer.allocate(1024 * 3);// 设置缓存区的大小:临时 private byte[] by = new byte[1024]; private InputStreamReader isr; private char[] ch = new char[1024]; /** *
 
   * 
   * 
* * @param src * @param dest * @throws IOException * */ public void convertionFile_nio(String src, String dest) throws IOException { fis = new FileInputStream(src); in = fis.getChannel(); fos = new FileOutputStream(dest); out = fos.getChannel(); inSet = Charset.forName("gbk"); outSet = Charset.forName("utf-8"); de = inSet.newDecoder(); en = outSet.newEncoder(); while (fis.available() > 0) { b.clear();// 清除标记 in.read(b); // 将文件内容读入到缓冲区内:将标记位置从0-b.capacity(), // 读取完毕标记在0-b.capacity()之间 b.flip();// 调节标记,下次读取从该位置读起 convertion = de.decode(b);// 开始编码 temp.clear();// 清除标记 temp = en.encode(convertion); b.flip(); // 将标记移到缓冲区的开始,并保存其中所有的数据:将标记移到开始0 out.write(temp); // 将缓冲区内的内容写入文件中:从标记处开始取出数据 } } /** *
 
   * 测试转码是否成功, 指定字符集读取文件 
   * 
* * @param src * 被复制文件全路径 * @param charset 解码字符集 * * @throws IOException 读取过程中的发生的异常 * */ public void read(String path, String charset) throws IOException { fis = new FileInputStream(path); isr = new InputStreamReader(fis, charset); while (fis.available() > 0) { int length = isr.read(ch); System.out.println(new String(ch)); } } /** *
 
   * 关闭所有流或通道 
   * 
* */ public void close() { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { CharsetConvertion n = new CharsetConvertion(); try { n.convertionFile_nio("C:/项目进度跟踪.txt", "C:/nio_write.txt"); // n.read("C:/nio_write.txt", "utf-8");// 正确 // n.read("C:/nio_write.txt", "gbk");//乱码 } catch (IOException e) { e.printStackTrace(); } finally { n.close(); } } }
Copy after login

The above is the detailed content of Example code summary of three methods to implement java character transcoding. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles