码迷,mamicode.com
首页 > 其他好文 > 详细

使用字节流复制文件

时间:2016-08-25 23:24:55      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Hello{
    public static void main(String args[]) throws Exception{
        String sourceFile = "D:" + File.separator + "Manor.jpg";
        String targetFile = "D:" + File.separator + "copy.jpg";
        File infile = new File(sourceFile);
        File outfile = new File(targetFile);
        copy(infile,outfile);
    }
    /**
     * 文件拷贝操作
     * @param infile
     * @param outfile
     * @return
     * @throws Exception
     */
    public static boolean copy(File infile,File outfile) throws Exception{
        InputStream input = null;
        OutputStream output = null;
        try{
            long start = System.currentTimeMillis();
            if(!outfile.getParentFile().exists()){
                outfile.getParentFile().mkdirs();
            }
            input = new FileInputStream(infile);
            output = new FileOutputStream(outfile);
            int temp = 0 ;
            while((temp = input.read()) != -1){
                output.write(temp);
            }
            long end = System.currentTimeMillis();
            System.out.println("花费时间:" + (end - start));
            return true;
        }
        catch (Exception e){
            throw e;
        }
        finally{
            if(input != null){
                input.close();
            }
            if(output != null){
                output.close();
            }
        }
        
    }
}

 改进代码,使用字节数组,更快

public static boolean copy(File infile,File outfile) throws Exception{
        InputStream input = null;
        OutputStream output = null;
        try{
            long start = System.currentTimeMillis();
            
            byte data[] = new byte[2048];
            input  = new FileInputStream(infile);
            output = new FileOutputStream(outfile);
            int temp = 0;
            while((temp = input.read(data)) != -1){
                output.write(data,0,temp);
            }
            
            long end = System.currentTimeMillis();
            System.out.println("花费时间:" + (end - start)/(double)1000 + "秒");
            return true;
        }
        catch (Exception e){
            throw e;
        }
        finally{
            if(input != null){
                input.close();
            }
            if(output != null){
                output.close();
            }
        }
        
    }

 

使用字节流复制文件

标签:

原文地址:http://www.cnblogs.com/cyxxzjp/p/5808406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!