文件夹复制

public static void main(String[] args) {

		File f1 = new File("D:/JavaTest");
		
		File f2 = new File("D:/JavaTest2");
		
		if (!f2.exists()) {
			
			f2.mkdir();
		}
		
		copyFile(f1, f2);
	}

	// 把 f1 文件夹 复制到 f2 文件夹
	public static void copyFile(File f1, File f2) {
		
		File[] files = f1.listFiles();
		
		if (files != null) {
			
			for (File file : files) {

				// 新文件的保存路径
				String path = f2.getAbsolutePath() + "/" + file.getName();
				
				if (file.isFile()) {
					
					// 如果是文件,就直接复制
					try {
						FileInputStream fis = new FileInputStream(file);
						
						FileOutputStream fos = new FileOutputStream(path, true);
						
						int length = 0;
						
						byte[] bytes = new byte[1024];
						
						while ((length = fis.read(bytes)) != -1) {
							
							fos.write(bytes, 0, length);
						}
						
						fos.close();
						fis.close();
					} catch (FileNotFoundException e) {

						e.printStackTrace();
					} catch (IOException e) {

						e.printStackTrace();
					}
				}else if (file.isDirectory()) {
					
					// 如果是文件夹,就先创建,然后再把内容复制到新文件夹中
					// 先创建不存在的文件夹
					File directoryFile = new File(path);
					
					directoryFile.mkdir();
					
					// 把文件夹中的内容拷贝到新文件夹中
					copyFile(file, directoryFile);
				}
			}
		}
	}

  

public static void main(String[] args) {

		folderCopy("D:\JavaTest", "E:\JavaTest");

		System.out.println("文件夹拷贝完成!");
	}

	public static void folderCopy(String str1, String str2) {

		// str1 为原来, str2 为复制后
		File file1 = new File(str1);

		File[] files1 = file1.listFiles();

		File file2 = new File(str2);

		if (!file2.exists()) {

			file2.mkdirs();
		}

		for (File file : files1) {

			if (file.isFile()) {

				fileCopy(file.getPath(), str2 + "\" + file.getName());
			}

			else if (file.isDirectory()) {

				folderCopy(file.getPath(), str2 + "\" + file.getName());
			}
		}
	}

	public static void fileCopy(String str1, String str2) {

		// 复制文件
		try {
			// 读 输入
			FileInputStream fis = new FileInputStream(str1);
			// 自动创建不存在的文件
			FileOutputStream fos = new FileOutputStream(str2, true);
			
			byte[] bytes = new byte[5];
			
			int length = 0;

			while ((length = fis.read(bytes)) != -1) {

				fos.write(bytes, 0, length);
			}
			// 先打开的后关闭,后打开的先关闭
			fos.close();
			
			fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

  

原文地址:https://www.cnblogs.com/niuxiao12---/p/7250002.html