ITPub博客

首页 > IT职业 > IT图书 > 字符集之间转换读取和写入

字符集之间转换读取和写入

IT图书 作者:samenzhou 时间:2021-09-09 09:52:45 0 删除 编辑

         

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;public class Main_GBK_Trans_UTF8 {	public static void main(String[] args) {		writeFileUseGBK();		readFileUseGBK();	}		public static void writeFileUseGBK() {		OutputStreamWriter ow=null;		try {			// 创建字节流			// OutputStreamWriter 是字符流通向字节流的桥梁			ow=new OutputStreamWriter(new FileOutputStream("E:/gbk.txt"), "GBK");			// 使用GBK编码写入,同时也只能使用GBK格式读取出来			ow.write("你好");		} catch (UnsupportedEncodingException e) {			e.printStackTrace();		} catch (FileNotFoundException e) {			e.printStackTrace();		} catch (IOException e) {			e.printStackTrace();		} finally {			if(ow!=null) {				try {					ow.close();				} catch (IOException e) {					e.printStackTrace();				}			}		}		System.out.println("end");	}		public static void readFileUseGBK() {		InputStreamReader in=null;		try {			// 创建字节流			// InputStreamReader 是字符流通向字节流的桥梁			// 使用GBK编码写入,同时也只能使用GBK格式读取出来			in=new InputStreamReader(new FileInputStream("E:/gbk.txt"), "GBK");			//in=new InputStreamReader(new FileInputStream("E:/gbk.txt"), "UTF-8");			char[] chs=new char[1024];			int len=-1;			while((len=in.read(chs))!=-1) {				System.out.println(new String(chs,0,len));				// 输出				// 你好			}					} catch (UnsupportedEncodingException e) {			e.printStackTrace();		} catch (FileNotFoundException e) {			e.printStackTrace();		} catch (IOException e) {			e.printStackTrace();		} finally {			if(in!=null) {				try {					in.close();				} catch (IOException e) {					e.printStackTrace();				}			}		}		System.out.println("end");	}}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/912/viewspace-2813955/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-19

  • 博文量
    104
  • 访问量
    1057