Java,複製文件夾及所有子文件,並排重

直接複製下面代碼即可,可直接使用

public static void moveFile(String orgin_path, String moved_path) {
		File[] files = new File(orgin_path).listFiles();
		for (File file : files) {
			if (file.isFile()) {// 如果是文件
				File movedFile = new File(moved_path + File.separator + file.getName());
                  // 如果文件已經存在則跳過
				if (movedFile.exists()) {
					System.out.println("文件已經存在1:" + file.getAbsolutePath());
					System.out.println("文件已經存在2:" + movedFile.getAbsolutePath());
					continue;
				} else {
					// 否則複製
					try {
						FileUtil.copyFile(file, movedFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			if (file.isDirectory()) {// 如果是目錄,就遞歸
				String childMPath = moved_path + File.separator + file.getName();
				new File(childMPath).mkdir();
				moveFile(file.getAbsolutePath(), childMPath);
			}
		} 
	}

	public static void copyFile(File resource, File target) throws Exception {
		FileInputStream inputStream = new FileInputStream(resource);
		BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
		FileOutputStream outputStream = new FileOutputStream(target);
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
		byte[] bytes = new byte[1024 * 2];
		int len = 0;
		while ((len = inputStream.read(bytes)) != -1) {
			bufferedOutputStream.write(bytes, 0, len);
		}
		bufferedOutputStream.flush();
		bufferedInputStream.close();
		bufferedOutputStream.close();
		inputStream.close();
		outputStream.close();
		long end = System.currentTimeMillis();
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章