java io 拷贝文件 复制文件夹

当没有文件时FileInputStream不会自动创建文件

package 学习;

import java.io.*;

/**
 * 
 * @author Administrator
 *将一个文件拷贝
 *取得源文件路径(必须存在)
 *通过FileInputStream取出文件内容,在通过FileOutputStream将数据写入目标地址文件
 */
public class Main {
	public static void main(String[] args) {
		try {
			FileInputStream in = new FileInputStream("c:/123.txt");
			FileOutputStream out = new FileOutputStream("c:/456.txt");
			
			//读出数据
			//2种方式,1一次性读完,数组要定义长度大于文件长度,不然会数据丢失
			//		2一次读取一个字节,到达文件尾返回-1
			
			/***第一种
			byte[] by = new byte[1024];
			int len = in.read(by); //数据长度
			写入到指定目标位置
			out.write(by);
			**/
			
			/**第二种**/
			int b;
			 while (-1 != (b = in.read())){ //返回值为-1到达末尾
				 //把获取到的字节写入目标文件
				 out.write(b);
			 }
			
			out.close();
			in.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

复制一份新的文件夹步骤

1 确定文件来源和目的地

2对来源文件进行判断是文件还是文件夹

是文件夹:将目的地新建一个相同的文件夹,递归调用,层层进入

是文件:直接将来源文件拷贝到新文件中

package 学习;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;

public class Main1 {
	public static void main(String[] args) {
		File oldFile = new File("c:/oldFile");
		File newFile = new File("c:/newFile");
		list(oldFile, newFile);
	}
	/**
	 *查找目录是文件夹,则继续递归, 是文件调用copy函数进行拷贝 
	 * @param oldFile
	 * @param newFile
	 */
	public static void list(File oldFile, File newFile){
		if (oldFile.isDirectory()){
			/**
			 * 是目录,在新的文件下创建同名文件夹,列出子文件,递归操作
			 */
			File file = new File(newFile, oldFile.getName()); //在newFile创建名为oldFile.getName()的文件夹
			file.mkdirs(); //创建
			File[] fileArr = oldFile.listFiles(); //列出子目录
			for (File f : fileArr){
				list(f, file);
			}
		}
		else{ //是文件,直接进行拷贝
			File file = new File(newFile, oldFile.getName());
			copy(oldFile, file);
		}
	}
	public static void copy(File oldFile, File newFile){
		try {
			FileInputStream in = new FileInputStream(oldFile);//从旧文件中获取
			FileOutputStream out = new FileOutputStream(newFile); //输出到新文件
			byte[] by = new byte[1024];
			in.read(by);
			out.write(by);
			out.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值