文件拷贝

在Java中,通过输入输出流实现一个文件的拷贝:

以.txt文件为例:

//文件拷贝;
class CopyFile {
	private CopyFile() {	
	}
	//判断要拷贝的源路径是否存在
	public static boolean isfileExists(String path) {
		return new File(path).exists();
	}
	//判断目标地址的父路径是否存在,不存在则创建
	public static void CreateParentDir(String path) {
		File file = new File(path);
		if(!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
	}
	//是否拷贝成功
	public static boolean isCopyFile(String sourcePath,String destPath) throws IOException {
		File file1 = new File(sourcePath);
		File file2 = new File(destPath);
		FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
			fileInputStream = new FileInputStream(file1);
			fileOutputStream = new FileOutputStream(file2);
			CopyFileHandle(fileInputStream,fileOutputStream);//完成具体的拷贝处理
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
			fileInputStream.close();
			fileOutputStream.close();
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return true;
	}
	//具体的拷贝操作
	public static void CopyFileHandle(InputStream fileInputStream, OutputStream outputStream) throws IOException {
		long start = System.currentTimeMillis();//开始计时
		//开辟缓冲区一次性读入多个内容
		byte[] data = new byte[1024];	
		while(fileInputStream.read(data) != -1) {//返回-1表示读取完毕
			 outputStream.write(data);
		}
		long end = System.currentTimeMillis();//结束计时
		System.out.println("拷贝所花时间:"+(end-start));
	}	
}
public class Main {
	public static void main(String[] args) throws IOException {
		String sourcePath = "C:\\Users\\CGX~LL\\Desktop\\singer.txt";//源路径
		String destPath = "C:\\Users\\CGX~LL\\Desktop\\singer2.txt";//目标路径
		if(CopyFile.isfileExists(sourcePath)) {
			CopyFile.CreateParentDir(destPath);
			System.out.println(CopyFile.isCopyFile(sourcePath,destPath)?"文件拷贝成功":"文件拷贝失败");
		}else {
			System.out.println("源文件不存在,无法拷贝");
		}
	}
}

创建了1KB的缓存空间,以提高效率;

你可能感兴趣的:(文件拷贝)