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

2022/5/4 20:13:03

本文主要是介绍【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-四种字符流使用实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程