编程语言
首页 > 编程语言> > 【java】学习路径42-四种字符流使用实例

【java】学习路径42-四种字符流使用实例

作者:互联网

 1-OutputStreamWriter

也可以在调用完write方法之后添加如下代码:

outputStreamWriter.flush();

养成良好的编程习惯。

@Test//写到硬盘 OutputStreamWriter
    public void testOutputStreamWriter(){
        OutputStreamWriter outputStreamWriter=null;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("字符流输出.txt");
            //可以指定默认编码,GBK,UTF-8,
            outputStreamWriter = new OutputStreamWriter(fileOutputStream,"GBK");

            outputStreamWriter.write('中');
            outputStreamWriter.write("你好");

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStreamWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 2-InputStreamReader

@Test//从硬盘读取 InputStreamReader
public void testInputStreamReader(){
    InputStreamReader inputStreamReader = null;

    try {
        FileInputStream fileInputStream = new FileInputStream("字符流输出.txt");
        //第二个参数 可以指定读取的编码
        inputStreamReader = new InputStreamReader(fileInputStream,"GBK");

        char[] data = new char[1024];
        int length = -1;
        while((length=inputStreamReader.read(data))>=0)
            System.out.print(new String(data,0,length));

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            inputStreamReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

使用上面的方法构造OutputStreamWriter&InputStreamReader时,需要再手动构造一个FileOutputStream&FileInputStream,比较麻烦

但是下面这两种没有办法指定编码格式。

 3-FileWriter

@Test//写进硬盘
public void testFileWriter(){
    FileWriter fileWriter = null;
    try {
        fileWriter = new FileWriter("字符流输出.txt");
        fileWriter.write("我使用了FileWriter直接写出字符流,非常方便\n");
        fileWriter.write("不需要像OutputStreamWriter那样\n");

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 4-FileReader

@Test//从硬盘读取
public void testFileRead(){
    FileReader fileReader = null;

    try {
        fileReader = new FileReader("字符流输出.txt");
        char[] chars = new char[1024];
        int length = -1;
        while((length=fileReader.read(chars))>=0)
            System.out.print(new String(chars,0,length));
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

标签:java,42,try,printStackTrace,length,实例,IOException,catch,new
来源: https://www.cnblogs.com/remyuu/p/16221882.html