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