文件字符流FileReader和FileWriter

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**
 * 使用字符流完成文件的复制
 * 
 * 1.如何区分是汉字还是英文
 *         英文字符一个字节, 第一个字节位是0
 *         汉字字符2个字节,第一个字节位是1
 *    
 * 2.其实只有字节流,没有字符流(字符流的底层使用的还是字节流)
 * 
 *  public FileReader(File file) throws FileNotFoundException {
        super(new FileInputStream(file));
    }
    
 * 3.字节流可以复制所有类型的文件
 *   字符流只能复制文本文件(记事本打开的文件)
 * 
 * @author Administrator
 *
 */
public class TestCopy3 {

    public static void main(String[] args) {
        Reader  fr = null;
        Writer  fw = null;
        try{
            //1.创建输入流和输出流
            fr = new FileReader(new File("e:/JDK_API_1_6_zh_CN.CHM"));
            fw = new FileWriter(new File("e:/JDK_API_1_6_zh_CN3.CHM"));
            
            //2.使用输入流和输出流
            //2.1指定一个中转站(一个字符数组)
            char [] cbuf = new char[1024];
            
            //2.2借助循环和中转站完成复制操作
            int len = fr.read(cbuf);
            while(len != -1){
                //输出
                //System.out.println(cbuf);
                //写
                fw.write(cbuf, 0, len);
                
                //读
                len = fr.read(cbuf);
            }
        }catch(FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //3.关闭输入流和输出流
            try {
                if(fr != null){
                    fr.close();
                }                
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            try {
                if(fw != null){
                    fw.close();
                }                
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
    }

}
 

猜你喜欢

转载自blog.csdn.net/qq_39209492/article/details/83591157