javaIO流中字符流的应用

五种方式实现文本文件复制(字符流)
* 基本字符流一次读写一个字符
* 基本字符流一次读写一个字符数组
* 高效字符流一次读写一个字符
* 高效字符流一次读写一个字符数组
* 高效字符流一次读写一个字符串

public class FiveKindIO {    
    public static void main(String[] args) throws Exception {
        //被复制的文件
        String src = "Regex.java";
        //复制到哪儿??
        String dest = "Regex02.java";
        //调用方法实现文件复制
        method4(src,dest);
    }
    
    
    //基本字符流一次读写一个字符
    public static void method1(String src,String test) throws Exception{
        FileReader fr = new FileReader(src);
        FileWriter fw = new FileWriter(test);
        
        
        int len =0;
        while((len=fr.read())!=-1){
            fw.write(len);
        }
        
        fr.close();
        fw.close();
    }
    
    
    //基本字符流一次读写一个字符数组
    public static void method2(String src,String test) throws Exception{
        FileReader fr = new FileReader(src);
        FileWriter fw = new FileWriter(test);
        
        char[] c = new char[1024];
        int len =0;
        while((len=fr.read(c))!=-1){
            fw.write(c, 0, len);
            fw.flush();
        }
        
        fr.close();
        fw.close();
    }

    
    //高效字符流一次读写一个字符
    public static void method3(String src,String test) throws Exception{
        BufferedReader br = new BufferedReader(new FileReader(src));
        BufferedWriter bw = new BufferedWriter(new FileWriter(test));
        
        
        int len=0;
        while((len=br.read())!=-1){
            bw.write(len);
            bw.flush();
        }
        
        br.close();
        bw.close();
    }

    
    //高效字符流一次读写一个字符数组
    public static void method4(String src,String test) throws Exception{
        BufferedReader br = new BufferedReader(new FileReader(src));
        BufferedWriter bw = new BufferedWriter(new FileWriter(test));
        
        char[] c = new char[1024];
        int len=0;
        while((len=br.read(c))!=-1){
            bw.write(c, 0, len);
            bw.flush();
        }
        
        br.close();
        bw.close();
    }
    
    
    //高效字符流一次读写一个字符串(读取一行)
    public static void method5(String src,String test) throws Exception{
        BufferedReader br = new BufferedReader(new FileReader(src));
        BufferedWriter bw = new BufferedWriter(new FileWriter(test));
        
        String line=null;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        
        br.close();
        bw.close();
        
    }
}

 

转载于:https://www.cnblogs.com/wlk-blog/p/6873988.html

你可能感兴趣的:(javaIO流中字符流的应用)