拷贝文件数据

来源:互联网 发布:java实现单例模式 编辑:程序博客网 时间:2024/06/06 03:58
/**     * 用途:拷贝文件数据     * @param sourceFilePath 参数:源文件的路径     * @param toFilePath 参数:目标的父级路径     * @throws FileNotFoundException     * 注意事项:目标的父级路径不存在就会新创建一个新的文件路径     */    public static void copyFile(String sourceFilePath, String toFilePath) throws FileNotFoundException {        // 初始化变量        FileInputStream in = null;        FileOutputStream ou = null;        File file = new File(sourceFilePath);        // 检测源文件是否存在        if (!file.exists()) {            throw new FileNotFoundException(file.getName() + "不存在!....");        }        // 目标文件夹是否存在。不存在就新建一个新的文件夹        File to = new File(toFilePath);        if (!to.exists()) {            to.mkdirs();        }        // 创建输入输出对象        in = new FileInputStream(file);        ou = new FileOutputStream(new File(toFilePath, file.getName()));        // 创建存储文件的byte数组        byte[] buffer = new byte[1024 * 8];        int len = 0;        // 拷贝文件        try {            while ((len = in.read(buffer)) != -1) {                ou.write(buffer, 0, len);            }        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {            if (in != null) {                try {                    in.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (ou != null) {                try {                    ou.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }
原创粉丝点击