Java实现拷贝文件详细代码

import java.io.*;
import java.util.Scanner;

public class CopyFile {
	public static void main(String args[]) {
		String src = "d:\\1.txt";
		String dest = "d:\\2.txt";
		System.out.println("---------------- 文件拷贝 ----------------");
		Scanner sca = new Scanner(System.in);
		System.out.print("键入要拷贝的源文件路径及文件名:" + src + "\n");
		try {
			copy(src, dest);
			System.out.println("-------文件拷贝成功-------");
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
			System.out.println("-------文件未找到-------");
		} catch (IOException e) {
			System.out.println("-------未知原因导致文件读写失败-------");
		}
	}

	/**
	 * 拷贝目标资源文件中
	 * @param src:指定目标资源
	 * @param dest:指定需要写入的文件
	 * @throws IOException:如果文件读取过程中出现位置错误则抛出IOException
	 */
	private static void copy(String src, String dest) throws IOException {
		// TODO Auto-generated method stub
		InputStream in = readFile(src);
		writeToFile(in, dest);
	}

	/**
	 * 读取文件,并使用InputStream关联读取的文件
	 * @param src:指定需要读取的文件
	 * @return 返回与文件相关联的流
	 * @throws FileNotFoundException
	 */
	private static InputStream readFile(String src)
			throws FileNotFoundException {
		// TODO Auto-generated method stub

		// 检测文件是否存在
		if (!existFile(src)) {
			throw new FileNotFoundException("-------指定目标资源不存在-------");
		}
		// 读取文件
		FileInputStream in = new FileInputStream(src);
		return in;
	}

	/**
	 * 判断文件是否存在
	 * @param src:需要判断的文件
	 * @return 如果存在返回true 如果不存在返回false
	 */
	private static boolean existFile(String src) {
		// TODO Auto-generated method stub
		File file = new File(src);
		if (file.exists()) {
			return true;
		}
		return false;
	}

	/**
	 * @param in
	 * @param dest
	 * @throws IOException
	 */
	private static void writeToFile(InputStream in, String dest)
			throws IOException {
		// TODO Auto-generated method stub

		if (!existFile(dest)) {
			File file = new File(dest);
			file.createNewFile();
		}
		FileOutputStream out = new FileOutputStream(dest);
		inToOut(in, out);
	}

	private static void inToOut(InputStream in, FileOutputStream out)
			throws IOException {
		// TODO Auto-generated method stub
		try {
			int len = 0;
			byte buffer[] = new byte[1024];
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} finally {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值