java学习之实现文件的复制

时间:2024-01-06 10:12:02
 package com.io;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 文件复制的实现
* @author ganhang
*
*/
public class HomeWork {
/**
*
* @param src 源文件的路径
* @param desc 目标文或文件夹的路径
* @throws FileNotFoundException
*/
public static void copyfile(File src, File desc)throws FileNotFoundException {
//判断文件路径是否正确是否是文件和文件夹
if (src == null || desc == null || src.isDirectory()||desc.isFile()) {
throw new FileNotFoundException("文件参数错误!");//抛出异常
} else {
if (!desc.exists())desc.mkdirs();//如果目标地址没有文件夹则创建文件夹
File file=new File(desc.getPath()+File.separator+src.getName());//创建目标文件路径和文件名的对象
try {
file.createNewFile();//创建文件
} catch (IOException e1) {
e1.printStackTrace();
}
FileInputStream fis = new FileInputStream(src);//文件读入流
FileOutputStream fos = new FileOutputStream(file,true);//文件写入流
BufferedInputStream bis=new BufferedInputStream(fis);//缓冲流
BufferedOutputStream bos=new BufferedOutputStream(fos);
byte[] b = new byte[210000000];//数据中转空间
try {
int len=-1;
while((len=bis.read(b))!=-1){//从源地址循环读入数据
bos.write(b, 0, len);//循环写入目的地址文件
}
fis.close();//关闭流
fos.close();
System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date())+"复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
//测试
public static void main(String[] args) {
File file1 = new File("f:\\电影\\万万没想到.mp4");//源文件必须是文件
File file2 = new File("f:\\视频\\");//目标文件必须是文件夹路径
try {
System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
copyfile(file1, file2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}