java 文件复制

1.需求

  根据原文件复制一份到指定位置

2.代码实现

需要导入:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

方法封装

private static final int BUFFER_SIZE = 16 * 1024;
/**
 * 
 <li>File文件复制自己封装的一个把源文件对象复制成目标文件对象</li>
 */
private boolean copy(File src, File dst) throws Exception {
    dst.setWritable(true, false);
    boolean result = false;
    InputStream in = null;
    OutputStream out = null;
    try {
        in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
        out = new BufferedOutputStream(new FileOutputStream(dst),
                BUFFER_SIZE);
        byte[] buffer = new byte[BUFFER_SIZE];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        result = true;
    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                throw new Exception(e);
            }
        }
        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                throw new Exception(e);
            }
        }
    }
    return result;
}

 

posted @ 2017-09-07 15:08  Marydon  阅读(426)  评论(0编辑  收藏  举报