复制文件的三种方法

复制文件的三种方法:

1、Files.copy(path, new FileOutputStream(dest));。

2、利用字节流。

3、利用字符流。

代码实现如下:


package com.tiger.io;

import java.io.*;
import java.nio.file.*;
/**
 * 复制文件的三种方式
 * @author tiger
 * @Date 2017年7月24日--上午8:52:54
 */
public class CopyFile {
	public static void main(String[] args) throws IOException, IOException {
		Path path = Paths.get("E:","17-06-15-am1.avi");
		String dest = "E:\\Copy电影.avi";
		copy01(path, dest);
		String src = "E:\\[Java典型应用彻查1000例:Java入门].pdf";
		String dest1 = "E:\\CopyFile.pdf";
		copy02(src, dest1);
		//copy03(src, dest1);
	}
	
	/**
	 * 利用Files工具copy
	 * @param path
	 * @param dest
	 * @throws IOException
	 * @throws IOException
	 */
	public static void copy01(Path path,String dest) throws IOException, IOException{
		//利用Files工具类对文件进行复制,简化编程,只需要写一句。
		Files.copy(path, new FileOutputStream(dest));
	}
	
	/**
	 * 利用字节流复制
	 * @param src
	 * @param dest
	 * @throws IOException
	 */
	public static void copy02(String src,String dest) throws IOException{
		InputStream is = new BufferedInputStream(new FileInputStream(src));
		OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
		//文件拷贝u,-- 循环+读取+写出
		byte[] b = new byte[10];//缓冲大小
		int len = 0;//接收长度
		//读取文件
		while (-1!=(len = is.read(b))) {
			//读入多少,写出多少,直到读完为止。
			os.write(b,0,len);
		}
		//强制刷出数据
		os.flush();
		//关闭流,先开后关
		os.close();
		is.close();
	}
	
	/**
	 * 字符流复制
	 * @param src
	 * @param dest
	 * @throws IOException
	 */
	public static void copy03(String src,String dest) throws IOException{
		//字符输入流
		BufferedReader reader = new BufferedReader(new FileReader(src));
		//字符输出流
		BufferedWriter writer = new BufferedWriter(new FileWriter(dest));
		char[] cbuf = new char[24];
		int len = 0;
		//边读入边写出
		while ((len = reader.read(cbuf)) != -1) {
			writer.write(cbuf, 0, len);
		}
		//关闭流
		writer.close();
		reader.close();
	}
}






  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ljt-tiger

thanks

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值