java中通过IO流实现文件的复制

一、通过节点流(InputStream、OutputStream)实现文件的复制:

        /**
	 * @param pathTo
	 *            :要保存复制内容的新文件路径,包含文件名及其后缀
	 * @param pathFrom
	 *            :要复制的源文件路径,包含文件名及其后缀
	 * @author Beauxie
	 */
	static void copyFile(String pathTo, String pathFrom) {

		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(new File(pathFrom));
			os = new FileOutputStream(new File(pathTo));
			byte[] bytes = new byte[1024];
			int count = 0;
			while ((count = is.read(bytes)) != -1) {
				System.out.println(new String(bytes));
				os.write(bytes, 0, count);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();// 关闭输入流,不然会浪费很多资源
					is = null;
				}
				if (os != null) {
					os.flush();// 刷新缓冲区中的内容
					os.close();// 关闭输出流
					os = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

 

二、通过处理流(BufferedReader 、BufferedWriter )实现文件复制:

	/**
	 * 该方法通过处理流实现文件的复制
	 * 
	 * @param pathFrom
	 *            :需要复制文件的路径,包含文件名及其后缀
	 * @param pathTo
	 *            :存放复制内容的文件路径,包含文件名及其后缀
	 * @author Beauxie
	 */
	private static void copyFile(String pathFrom, String pathTo) {

		BufferedReader br = null;
		BufferedWriter bw = null;
		try {

			/*
			 * InputStream is=new FileInputStream(pathFrom); InputStreamReader
			 * ir=new InputStreamReader(is); br=new BufferedReader(ir);
			 */
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					pathFrom)));

			/*
			 * OutputStream os=new FileOutputStream(pathTo); OutputStreamWriter
			 * or=new OutputStreamWriter(os); bw=new BufferedWriter(or);
			 */
			bw = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(pathTo)));

			String str = null;
			while ((str = br.readLine()) != null) {
				bw.write(str + "\r\n");
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
					br = null;
				}
				if (bw != null) {
					bw.flush();
					bw.close();
					bw = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值