IO流学习总结-转换流

2017-11-15  本文已影响0人  秃头大叔

转换流

字节流转换为字符流

通过字符流OutputStreamWriter,InputStreamReader 将字节流转换为字符流;
主要目的:由于字符流内置GBK的编码格式,在指定编码格式时,可通过转换流来规定编码格式来避免乱码;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class inputstreamReader {
    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream("copyfile3.txt"),"UTF-8");  // InputStreamReader 将字节流转换为FileReader字符流,并规定编码格式为UTF-8;
        OutputStreamWriter osr = new OutputStreamWriter(new FileOutputStream("copyfile2.txt"),"UTF-8");
        // 同样在转换为字符流后可利用缓冲区
        BufferedReader br = new BufferedReader(isr);
        BufferedWriter bw = new BufferedWriter(osr);
        String str;
        while((str = br.readLine()) != null){
            System.out.println(str);   
            bw.write(str);
            bw.newLine();
            bw.flush();
        }
        bw.close();
        br.close();
    }
}


  内容无太多备注,仅仅用来快速回忆知识点,毕竟自学的路相对漫长,前端的工作还是要继续滴;
上一篇下一篇

猜你喜欢

热点阅读