java学习之实现文件的复制

 1 package com.io;
 2 import java.io.*;
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 /**
 6  * 文件复制的实现
 7  * @author ganhang
 8  * 
 9  */
10 public class HomeWork {
11     /**
12      * 
13      * @param src 源文件的路径
14      * @param desc 目标文或文件夹的路径
15      * @throws FileNotFoundException
16      */
17     public static void copyfile(File src, File desc)throws FileNotFoundException {
18         //判断文件路径是否正确是否是文件和文件夹
19         if (src == null || desc == null || src.isDirectory()||desc.isFile()) {
20             throw new FileNotFoundException("文件参数错误!");//抛出异常
21         } else {
22             if (!desc.exists())desc.mkdirs();//如果目标地址没有文件夹则创建文件夹
23             File file=new File(desc.getPath()+File.separator+src.getName());//创建目标文件路径和文件名的对象
24             try {
25                 file.createNewFile();//创建文件
26             } catch (IOException e1) {
27                 e1.printStackTrace();
28             }
29             FileInputStream fis = new FileInputStream(src);//文件读入流
30             FileOutputStream fos = new FileOutputStream(file,true);//文件写入流
31             BufferedInputStream bis=new BufferedInputStream(fis);//缓冲流
32             BufferedOutputStream bos=new BufferedOutputStream(fos);
33             byte[] b = new byte[210000000];//数据中转空间
34             try {
35                 int len=-1;
36                 while((len=bis.read(b))!=-1){//从源地址循环读入数据
37                     bos.write(b, 0, len);//循环写入目的地址文件
38                 }
39                 fis.close();//关闭流
40                 fos.close();
41                 System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date())+"复制成功!");
42             } catch (IOException e) {
43                 e.printStackTrace();
44             }
45         }
46     }
47     //测试
48     public static void main(String[] args) {
49         File file1 = new File("f:\电影\万万没想到.mp4");//源文件必须是文件
50         File file2 = new File("f:\视频\");//目标文件必须是文件夹路径
51         try {
52             System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
53             copyfile(file1, file2);
54         } catch (FileNotFoundException e) {
55             e.printStackTrace();
56         }
57     }
58 }
原文地址:https://www.cnblogs.com/ganhang-acm/p/5154307.html