Java IO 转换流的编码解码

来源:互联网 发布:vscode xp版本 编辑:程序博客网 时间:2024/06/06 01:32
package io.transstream.demo;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import javax.print.attribute.standard.OutputDeviceAssigned;import com.sun.org.apache.xml.internal.serialize.OutputFormat;public class TransStreamDemo3 {public static void main(String[] args) throws IOException {readText_2();}private static void readText_2() throws IOException {InputStreamReader isr=new InputStreamReader(new FileInputStream("gbk.txt"),"UtF-8");char []buf=new char[10];int len=isr.read(buf);String str=new String(buf, 0, len);System.out.println(str);isr.close();}private static void readText_1() throws IOException {FileReader fr=new FileReader("u8_1.txt");char []buf=new char[10];int len=fr.read(buf);String str=new String(buf, 0, len);System.out.println(str);fr.close();}private static void writeText_3() throws IOException {OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("u8_1.txt"),"utf-8");osw.write("你好");osw.close();}private static void writeText_2() throws IOException {OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("gbk_2.txt"));OutputStreamWriter osw2=new OutputStreamWriter(new FileOutputStream("gbk_2.txt"),"gbk");/* * 这两句代码的功能是等同的 * FileWriter:其实就是转换流指定了本机默认码表的体现 而且这个转换流的子类对象 可以方便操作文本文件 *简单说:操作文件的字节流+本机默认的编码表 *这是按照默认码表来操作文件的便捷类 *如果操作文本文件需要明确 具体的编码 FileWriter就不行了 必须用转换流  * */osw.write("你好");osw.close();}private static void writeText_1() throws IOException {FileWriter fw=new FileWriter("gbk.txt");fw.write("你好");fw.close();}}

阅读全文
0 0
原创粉丝点击