java复制目录

	/**
	 * 复制目录
	 * @param sourcePath
	 * @param targetPath
	 * @throws FileNotFoundException 
	 */
	public static void copyFolder(File sourcePath, String targetPath) throws FileNotFoundException {
		if (!sourcePath.exists()) { //源目录不存在
			throw new FileNotFoundException(sourcePath.getAbsolutePath() + " not found");
		}
		if (!new File(targetPath).exists()) { //创建目标目录
			new File(targetPath).mkdirs();
		}
		FileInputStream inputStream = null;
        FileOutputStream outputString = null;
        FileChannel channelIn = null;
        FileChannel channelOut = null;
        String targetFile = null;
		for (File file: sourcePath.listFiles()) {
			targetFile = targetPath + File.separator + file.getName();
			if (file.isFile()) {
				try {
					inputStream = new FileInputStream(file);
					outputString = new FileOutputStream(targetFile);
					channelIn = inputStream.getChannel();
					channelOut = outputString.getChannel();
					channelIn.transferTo(0, channelIn.size(), channelOut);
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						inputStream.close();
						outputString.close();
						channelIn.close();
						channelOut.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			} else {
				copyFolder(file, targetFile);
			}
		}
	}

	public static void main(String[] args) throws FileNotFoundException {
		String webRootPath = "D:/test/webRoot";
		File resourceFile = new File("D:/test/webRoot/resource/demo");
		if (!resourceFile.exists()) {
			throw new FileNotFoundException(resourcePath + " not found");
		}	
		copyFolder(resourceFile, webRootPath);	
	}

 

你可能感兴趣的:(java)