Java的输入/输出——转换流

输入字节流——字符流:InputStreamReader类

InputStreamReader类是Reader的子类,可以将一个字节输入流转变成字符输入流,在转换时默认使用本地操作系统的字符编码或者指定其他字符编码,常用方法如下:

这里写图片描述

输出字节流——字符流:OutputStreamWriter类

OutputStreamWriter类是Writer的子类,可以将一个字节输出流转变成字符输出流,在转换时默认使用本地操作系统的字符编码或者指定其他字符编码,常用方法与InputStreamReader类方法类似。

终端都是字节实现的;

这里写图片描述

public class TestDemo3 {


    public static void main(String[] args) {
        File file = new File("D:\\lzq/java.txt");
        //output(file);
        //input(file);
        File file1 = new File("D:\\lzq/hello.txt");
        //test1(file1);
        test2(file1);
    }
    /**
     * 输入字节——字符流
     * @param file
     */
    public static void input(File file) {
        try {
            FileInputStream fin = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fin);
            System.out.println("系统默认字符:"+isr.getEncoding());
            int tmp = 0;
            while((tmp = isr.read()) != -1) {
                System.out.println((char)tmp);
            }
            isr.close();
            fin.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
        System.out.println();
    }
    /**
     * 将一个字节流中的字节解码成字符 
     * @param file
     */
    public static void test1(File file) {
        try {
            InputStream in = new FileInputStream(file);
            InputStreamReader str = new InputStreamReader(in); //字节流——>字符流
            char[] ch = new char[1024];
            int len = str.read(ch);  //读取字符流中的数据,用char类型的数组接收
            System.err.println(new String(ch,0,len));
            str.close();
        }catch(IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 输出字节——字符流
     * @param file
     */
    public static void output(File file) {
        try {
            FileOutputStream fout = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fout);
            String str = "宝剑锋从磨砺出,梅花香自苦寒来";
            osw.write(str);
            osw.close();
            fout.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
        System.out.println();
    }
    /**
     * 将写入的字符编码成字节后写入一个字节流
     * @param file
     */
    public static void test2(File file) {
        try {
            OutputStream out = new FileOutputStream(file);
            OutputStreamWriter x = new OutputStreamWriter(out);
            String str = "万岁";
            x.write(str);
            x.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

运行结果:


系统默认字符:GBK
宝
剑
锋
从
磨
砺
出
,
梅
花
香
自
苦
寒
来

以上程序需要注意的是,一定要先执行osw.close()方法再执行fout.close()方法,否则报错

猜你喜欢

转载自blog.csdn.net/qq2899349953/article/details/81189480