IO流复制文件及文件夹

1.复制文件:

提示:可使用字节流和字符流实现

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyMp4 {

	public static void main(String[] args) {
		// 在指定路径下创建文件
		File file = new File("E:/java/land.mp4");
		try {
			// 字节输入流:把硬盘中的文件读取到内存,相当于打开文件
			FileInputStream in = new FileInputStream(file);
			// 建立一个缓存区
			byte[] b = new byte[(int) file.length()];
			// 读取文件内容到缓冲区
			in.read(b);
			// 关闭字节流输入
			in.close();
			// 字节输出流,是从内存写入数据到硬盘文件
			FileOutputStream o = new FileOutputStream("E:/aa/a.mp4", true);
			// 讲缓存区的b写入指定文件夹
			o.write(b);
			// 关闭字节流输出
			o.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

2.复制文件夹

提示:可使用字节流和字符流进行实现

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class copyDirDemo {

	public static void main(String[] args) {
		try {
			copyDirDemo.copyDir(new File("E:/aa"), new File("E:/java/bb"));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void copyDir(File oldFile, File newFile) throws IOException {
		// if(!newFile.exists()){
		newFile.mkdirs();
		// }
		File[] files = oldFile.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				copyDir(file, new File(newFile.getAbsolutePath() + "//" + file.getName()));
			}
			if (file.isFile()) {
				/**
				 * 使用字节流复制文件夹
				 */
				/*
				 * FileInputStream fis=new FileInputStream(file);
				 * FileOutputStream fos=new
				 * FileOutputStream(newFile.getAbsolutePath()+"\\"+file.getName(
				 * )); byte[] b=new byte[1024*1024]; int length=0;
				 * while((length=fis.read(b))!=-1){ fos.write(b,0,length);}
				 * fos.close(); fis.close();
				 */
				/**
				 * 使用字符流复制文件夹
				 */
				BufferedReader in = new BufferedReader(new FileReader(file));
				BufferedWriter out = new BufferedWriter(
						new FileWriter(newFile.getAbsolutePath() + "\\" + file.getName()));
				String line = null;
				while ((line = in.readLine()) != null) {
					out.write(line);
					out.newLine();
				}
				in.close();
				out.close();
			}
		}
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值