从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

/*
 * 目的:从键盘接收两个文件夹路径,把其中一个文件夹(包含内容)拷贝到另一个文件夹中
 * */
public class CopyPath2Path {
	/*mian*/
	public static void main(String[] args) throws Exception{
		copyPath2Path();
	}
	/*目的:从键盘接收两个文件夹路径,把其中一个文件夹(包含内容)拷贝到另一个文件夹中*/
	public static void copyPath2Path() throws Exception{
		/*键盘录入路径 */
		Scanner sc = new Scanner(System.in);
		/*创建源路径对象*/
		File fileSource=null;
		/*创建目标路径对象*/
		File filePath=null;
		/*循环录入对象路径*/
		while(true){
			System.out.println("请输入要拷贝的源路径(直接粘贴windows格式路径)"); 
			fileSource=new File(trans(sc.next()));
			System.out.println("请输入拷贝后文件存放的目标路径(直接粘贴windows格式路径)");
			filePath=new File(trans(sc.next()));
			/*判断输入的路径是否合法:路径是否存在,路径是否是文件夹,源路径是否包含目标路径*/
			if(!fileSource.isDirectory()||!filePath.isDirectory()||(filePath.toString()).contains(fileSource.toString())){
				System.out.println("输入的路径不合法,请重新输入");
				continue;
			}else{
				sc.close();
				break;
			}
		}
		/*调用newFile(),创建新文件并调用fileCopy方法拷贝内容 */
		newFile(fileSource,filePath);
	}
	/* 转换路径格式: 将Scanner录入的的windows格式路径转为java认可的路径 */
	public static String trans(String in) {
		StringBuffer sbIn = new StringBuffer();
		char[] cArr = in.toCharArray();
		for (char c : cArr) {
			sbIn.append(c);
			if (c == '\\')
				sbIn.append("\\");
		}
		return sbIn.toString();
	}
	/*
	 * 递归调用 
	 * 在目标路径创建对应名称的文件夹,遍历源文件夹的内容,是文件夹就递归,是文件就在新建文件夹下创建对应文件
	 */
	public static void newFile(File fileSource, File fileFolder) throws Exception{
		/*先创建文件夹:以目标路径文件夹为相对路径,以传入的文件夹的名字为名*/
		File fileNewFolder=new File(fileFolder,fileSource.getName());
		fileNewFolder.mkdirs();//必须创建目录,后续才能建立实际文件
		File[] fileArr = fileSource.listFiles();
		for (File f : fileArr) {
			if (f.isDirectory()) {
				newFile(f, fileNewFolder);
			} else {
				/*创建文件对象:以新建文件夹为相对路径,以源文件的名字为名*/
				File fileNewFile = new File(fileNewFolder, f.getName());
				fileCopy(f, fileNewFile);
			}
		}
	}

	/*
	 * 传入两个文件,将1的内容,拷贝给2
	 * 带异常处理
	 */
	public static void fileCopy(File file1, File file2) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		int i = 0;
		byte[] b = new byte[8192]; //缓冲区大小取8192
		try {
			fis = new FileInputStream(file1);
			fos = new FileOutputStream(file2);
			while ((i = fis.read(b)) != -1) {
				fos.write(b, 0, i);
			}
		} catch (IOException ioe) {
			System.out.println(ioe + "文件<<" + file1 + ">>拷贝失败");
			throw new RuntimeException("IO对象创建异常");
		} finally {
			if (fos != null) { // 两个流对象逐个关闭
				try {
					fos.close();

				} catch (IOException ioe) {
					throw new RuntimeException("资源关闭失败");
				} finally {
					if (fis != null) {
						try {
							fis.close();
							System.out.println("文件<<" + file1 + ">>拷贝成功");
						} catch (IOException ioe) {
							throw new RuntimeException("资源关闭失败");
						}
					}
				}
			}
		}
	}

}

猜你喜欢

转载自blog.csdn.net/hssykey/article/details/81262705