IO练习--字符文件copy

2016-11-06  本文已影响11人  比轩

刚刚学习完java.io的部分东西,写一个文件复制的小练习,包括了异常的处理(没有考虑新复制出来的文件存在的情况,直接会被覆盖掉)。
code


package io;

/*
 * 一个文本文件复制的demo
 * 1.单字节复制
 * 2. 数组复制
 */

import java.io.*;

public class FileCopyTest {
    public static void main(String[] args) {
        long s = System.currentTimeMillis();
        FileCopyByByte("test.txt","test1.txt");
        
        long m = System.currentTimeMillis();
        FileCopyByBytes("test.txt","test2.txt");
        long e = System.currentTimeMillis();
        
        
        System.out.println("单字节复制用时:" + (m-s));
        System.out.println("数组复制用时:" + (e-m));
    }
    
    /*
     * 1.单字节复制 FileCopyByByte
     *  结果:7757ms
     */
    public static void FileCopyByByte(String fileAddress,String NewFileAddress){
        
        FileReader fr = null;
        FileWriter fw = null;
        
        try{
            
            fr = new FileReader(fileAddress);
            fw = new FileWriter(NewFileAddress);
            
            int len = 0;
            while((len = fr.read()) != -1){
                fw.write(len);
                fw.flush();
            }
            
        }catch(IOException e){
            throw new RuntimeException("文件复制失败");
            
        }finally{
            try{
                if(fw != null)
                    fw.close();
            }catch(IOException e){
                throw new RuntimeException("关闭复制文件资源失败");
            }
            try{
                if(fr != null)
                    fr.close();
            }catch(IOException e){
                throw new RuntimeException("关闭复制源资源失败");
            }

        }

    }
    
    /*
     * 1.数组复制 FileCopyByBytes
     * 结果:282ms
     */
    public static void FileCopyByBytes(String fileAddress,String NewFileAddress){
        
        //创建读取写入的对象
        FileReader fr = null;
        FileWriter fw = null;
        
        try{
            //初始化读取写入的对象
            fr = new FileReader(fileAddress);
            fw = new FileWriter(NewFileAddress);
            //len存取每次读取的字符数,ch存储每次读取的内容
            int len = 0;
            char[] ch = new char[1024];
            
            //while循环写入并flush
            while((len = fr.read(ch)) != -1){
                fw.write(ch,0,len);
                fw.flush();
            }
            
            
        }catch(IOException e){
            throw new RuntimeException("文件复制失败");
            
        }finally{  //在finally里面关闭所有资源,关闭失败直接扔一个runtime异常,让程序停止
            try{
                if(fw != null)
                    fw.close();
            }catch(IOException e){
                throw new RuntimeException("关闭复制文件资源失败");
            }
            try{
                if(fr != null)
                    fr.close();
            }catch(IOException e){
                throw new RuntimeException("关闭复制源资源失败");
            }

        }

    }
}

上一篇下一篇

猜你喜欢

热点阅读