Java、IO流之转换流详解

转换流属于字符流,也是处理流的一种。

作用:提供了在字节流和字符流之间的转换。 JavaAPI提供了两个转换流:

    InputStreamReader:将一个字节的输入流转换为一个字符的输入流。 OutputStreamWriter:将一个字符的输出流转换为一个字节的输出流。

意义:可以把我们不好理解的字节转换成可以理解的字符(解码),然后把我们可以理解的字符再转换成字节存进去(编码)。

前置知识: ,

InputStreamReader & OutputStreamWriter

示例代码1: 使用字节输入流获取数据,转换成字符流获取数据,输出到控制台。

@Test
    public void InputStreamReaderTest(){
          
   
        InputStreamReader inputStreamReader = null;
        try {
          
   
            FileInputStream fileInputStream = new FileInputStream("jdbc.properties");
            //参数2指明了字符集,不写则默认系统字符集,具体使用哪个字符集,取决于文件保存时使用的字符集
            inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
            int len;
            char[] data = new char[1024];
            while((len = inputStreamReader.read(data)) != -1){
          
   
                System.out.println(new String(data,0,len));
            }
        } catch (IOException e) {
          
   
            e.printStackTrace();
        }finally {
          
   
            try {
          
   
                if (inputStreamReader != null) inputStreamReader.close();
            } catch (IOException e) {
          
   
                e.printStackTrace();
            }
        }
    }

示例代码2: 使用字节输入流获取数据,转换为字符输入流获取数据,

@Test
    public void InputStreamReaderTest1(){
          
   
        InputStreamReader inputStreamReader = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
          
   
            File file1 = new File("hello.txt");
            File file2 = new File("hello_gbk.txt");

            FileInputStream fileInputStream = new FileInputStream(file1);
            FileOutputStream fileOutputStream = new FileOutputStream(file2);

            inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
            outputStreamWriter = new OutputStreamWriter(fileOutputStream,"gbk");

            int len;
            char[] data = new char[1024];
            while((len = inputStreamReader.read(data)) != -1){
          
   
                outputStreamWriter.write(data,0,len);
            }
        } catch (IOException e) {
          
   
            e.printStackTrace();
        }finally {
          
   
            try {
          
   
                if(inputStreamReader != null) inputStreamReader.close();
            } catch (IOException e) {
          
   
                e.printStackTrace();
            }
            try {
          
   
                if(outputStreamWriter != null) outputStreamWriter.close();
            } catch (IOException e) {
          
   
                e.printStackTrace();
            }
        }
    }
经验分享 程序员 微信小程序 职场和发展