Java复制某一路经下的文件(包含子文件、子文件夹)到另一个路径下

上代码:

1、从srcFolder文件夹的东西复制到destFolder文件夹:

    public static void copyFolder(String srcFolder, String destFolder) {
		File srcF = new File(srcFolder);

		File flist[] = srcF.listFiles();
		for (File f : flist) {
			if (f.isFile()) {// 如果是文件
				File newDestF = new File(destFolder + "/" + f.getName());
				copyFile(f, newDestF);
			} else if (f.isDirectory()) {// 如果f是文件夹
				File mkfile = new File(destFolder + "/" + f.getName());
				if (!mkfile.exists()) {//如果目标文件夹不存在
					mkfile.mkdir();// 则创建文件夹
				}
				copyFolder(srcFolder + "/" + f.getName(), destFolder + "/" + f.getName());
			}
		}
	}

2、copyFile函数:把srcF文件复制到destF文件:

	public static void copyFile(File srcF, File destF) {
		try (FileInputStream fis = new FileInputStream(srcF); FileOutputStream fos = new FileOutputStream(destF);) {
			byte[] buf = new byte[1024];
			int bytesRead;
			while ((bytesRead = fis.read(buf)) != -1) {
				fos.write(buf, 0, bytesRead);
			}

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

3、测试函数:

public static void main(String[] args) {
		copyFolder("F:/StreamTest", "F:/StreamTest2");
	}

将F:/StreamTest路径下所有文件、文件夹复制到F:/StreamTest2中

初始:

运行完:


记录点滴 2019/08/27

猜你喜欢

转载自blog.csdn.net/a1085578081/article/details/100100075