工具类——利用递归和过滤流复制文件到目标路径

复制文件工具类

复制单一文件

/*
	 * 复制一个文件的封装方法
	 */
	public static void copyOneFileTo(File fileSource, File fileAim) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(fileSource));
			bos = new BufferedOutputStream(new FileOutputStream(fileAim));
			byte[] b = new byte[1024 * 8];
			int n;
			while ((n = bis.read(b)) != -1) {
				bos.write(b);
				bos.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

利用递归遍历将所要复制的目录下的文件都遍历出来,然后调用复制单一文件的方法将目录下的非文件夹文件复制到目标路径。

/*
	 * 递归遍历了文件,并复制
	 */
	public static void copyFile(File fileInTo, File fileOutTo) {
		File[] listFiles = fileInTo.listFiles();
		for (File file : listFiles) {
			if (file.isDirectory()) {

				File file2 = new File(fileOutTo.getAbsolutePath() + "/" + file.getName());
				file2.mkdirs();
				copyFile(file, file2);
			} else {
				copyOneFileTo(file, new File(fileOutTo.getAbsolutePath() + "/" + file.getName()));
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/weixin_44211733/article/details/85194946