java拷貝目錄及其子目錄、文件,到另外一個目錄

	/**
	 * 複製一個目錄及其子目錄、文件到另外一個目錄
	 * @param src
	 * @param dest
	 * @throws IOException
	 */
	private void copyFolder(File src, File dest) throws IOException {
		if (src.isDirectory()) {
			if (!dest.exists()) {
				dest.mkdir();
			}
			String files[] = src.list();
			for (String file : files) {
				File srcFile = new File(src, file);
				File destFile = new File(dest, file);
				// 遞歸複製
				copyFolder(srcFile, destFile);
			}
		} else {
			InputStream in = new FileInputStream(src);
			OutputStream out = new FileOutputStream(dest);

			byte[] buffer = new byte[1024];

			int length;
			
			while ((length = in.read(buffer)) > 0) {
				out.write(buffer, 0, length);
			}
			in.close();
			out.close();
		}
	}


PS: apache commons-io包,FileUtils有相關的方法,IOUtils一般是拷貝文件。

刪除目錄結構                    FileUtils.deleteDirectory(dest);

遞歸複製目錄及文件        FileUtils.copyDirectory(src, dest);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章