1. 程式人生 > >java轉換流、亂碼之編碼與解碼

java轉換流、亂碼之編碼與解碼

package com.bjsxt.io.convert;

import java.io.UnsupportedEncodingException;

public class ConverDemo01 {

	/**
	 * @param args
	 * @throws UnsupportedEncodingException 
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		String str ="中國";
		byte[] data =str.getBytes();
		//位元組數不完整
		System.out.println(new String(data,0,3));
		
		test1();
		
	}
	/**
	 * 編碼與解碼字符集必須相同,否則亂碼
	 * @throws UnsupportedEncodingException 
	 */
	public static void test1() throws UnsupportedEncodingException{
		//解碼 byte -->char
				String str ="中國"; //gbk 
				//編碼 char -->byte
				byte[] data =str.getBytes();
				//編碼與解碼字符集同一
				System.out.println(new String(data));
				data =str.getBytes("utf-8"); //設定編碼字符集
				//不同一出現亂碼
				System.out.println(new String(data));
				
				//編碼
				byte[] data2 = "中國".getBytes("utf-8");
				//解碼
				str=new String(data2,"utf-8");
				System.out.println(str);
	}

}
package com.bjsxt.io.convert;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * 轉換流: 位元組轉為字元
 * 1、輸出流 OutputStreamWriter 編碼
 * 2、輸入流 InputStreamReader  解碼
 * 
 * 確保源不能為亂碼
 * @author Administrator
 *
 */
public class ConverDemo02 {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		//指定解碼字符集
		BufferedReader br =new BufferedReader(
				new InputStreamReader(
					new BufferedInputStream(
							new FileInputStream( 
									new File("E:/xp/test/Demo03.java"))),"UTF-8")
				);
		
		// InputStreamReader用於實現位元組轉換為字元,解碼,用utf-8解碼
		//寫出檔案 編碼
		BufferedWriter bw =new BufferedWriter(
				new OutputStreamWriter(
					new BufferedOutputStream(	
					new FileOutputStream(new File("E:/xp/test/encode.java")))));
				
		String info =null;
		while(null!=(info=br.readLine())){
			//System.out.println(info);
			bw.write(info);
			bw.newLine();
		}
		bw.flush();
		bw.close();
		br.close();
	}

}