读书人

资料copy工具类的简单实现

发布时间: 2012-08-22 09:50:34 作者: rapoo

文件copy工具类的简单实现

这个工具类是我模仿Spring的工具类实现的,从模仿spring的编程风格开始塑造自己的编程风格。

package com.amuse.utils;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;/** * 类FileCopyUtil.java的实现描述:FileCopyUtil.java * @author yongchun.chengyc 2012-3-7 下午6:37:05 */public class FileCopyUtil {    /** 字节缓冲数组的大小 */    private static final int BUFFER_SIZE = 4096;    /**     * 将 File in 的内容复制到 File out 中     *      * @param in 源文件     * @param out 目标文件     * @return the number of bytes copied     * @throws IOException 如果 I/O errors     */    public static int copy(File in, File out) throws IOException {        if ((in == null) || (out == null)) {            throw new IOException("No input File specified or No output File specified");        }        return copy(new BufferedInputStream(new FileInputStream(in)),                    new BufferedOutputStream(new FileOutputStream(out)));    }    /**     * @param in 源stream     * @param out 目标stream     * @return the number of bytes copied     * @throws IOException 如果 I/O errors     */    private static int copy(BufferedInputStream in, BufferedOutputStream out) throws IOException {        if ((in == null) || (out == null)) {            throw new IOException("No InputStream specified or No OutputStream specified");        }        int byteCount = 0;        byte[] buffer = new byte[BUFFER_SIZE];        int bytesRead = -1;        if ((bytesRead = in.read(buffer)) != -1) {            out.write(buffer, 0, bytesRead);            byteCount += bytesRead;        }        out.flush();        return byteCount;    }    public static void main(String[] args) throws IOException {        File in = new File("/home/drew/桌面/test");        File out = new File("/home/drew/桌面/test1");        FileCopyUtil.copy(in, out);    }}
?

读书人网 >编程

热点推荐