Java第十一篇:FTPClient将指定目录下的文件批量复制到另一个目录下

FtpClient的复制功能实现

/**
* 将指定文件目录下的多个文件复制到另一个指定文件中来
* @param fileNames 要复制的文件名
* @param fromPath 从哪个文件目录中复制
* @param toPath 复制到哪个目录
* @return true-复制成功,false-复制失败
* @throws IOException
*/
public boolean batchCopyFileToPath(List<String> fileNames, String fromPath, String toPath) throws IOException{
	//如果toPath不存在,则创建该目录
	if(!mkDir("",toPath)){
		logger.error("创建"+ toPath+"失败");
		return false;
	}
	if(!this.ftpClient.isConnected()){
		return false;
	}
	for(String fileName : fileNames){
		//设置当前处理文件夹的层级
		this.ftpClient.changeToParentDirectory();
		this.ftpClient.changeToParentDirectory();
		this.ftpClient.setControlEncoding("UTF-8");
		this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
		this.ftpClient.setBufferSize(1024);
		this.ftpClient.enterLocalPassiveMode();
		Inputstream ins = null;
		if(this.ftpClient.changeWorkingDirectory(formatPath(fromPath))){
			ins = this.ftpClient.retrieveFileStream(fileName);
			//使用retrieveFileStream必须调用getReply(),避免下次为空
			this.ftpClient.getReply();
		}
		//返回正确的目录
		this.ftpClient.changeToParentDirectory();
		this.ftpClient.changeToParentDirectory();
		if(this.ftpClient.changeWorkingDirectory(formatPath(fromPath))){
			if(!this.ftpClient.storeFile(fileName,ins)){
				return false;
			}
		}
		if(ins != null){
			ins.close();
		}
	}
}

private String formatPath(String filePath){
	if(StringUtils.isBlank(filePath)){
		filePath = "~/";
	}else{
		filePath = "~/" + filePath;
	}
	if(!filePath.endWith("/")){
		filePath += "/";
	}
	return filePath;
}

你可能感兴趣的:(java,java,开发语言)