spring定时把服务器中的文件传输到ftp服务器上并且删除服务器中传输后的文件

/**
 * @author zyt
 * @version : 2017年2月27日
 */
public class FtpUtils {
	/** 
	 * 复制某个文件夹下面的所有内容到ftp服务器上
	 * @param realPath String 项目的真实路径 如:D:\tomcat7x64\tomcat7x64\webapps\lnwqxsgj\
	 * @param oldPath String 原文件夹的真实路径 如:D:\tomcat7x64\tomcat7x64\webapps\lnwqxsgj\file
	 * @param newPath FtpClient ftp服务器 
	 * @return boolean
	 * 
	 */ 
	public static boolean copyFolder(String realPath,File oldFile,FtpClient ftpClient) { 
		try {
			if (!oldFile.exists()) {
				System.out.println("FtpUtils.copyFolder()找不到指定的文件!");
				return false;
			}
			//如果是文件夹
			if (oldFile.isDirectory()) {
				if (oldFile.list().length == 0) {
					try {
						//得到从项目名开始的子目录
						String dir = oldFile.toString().replace(realPath,"");  
						if (!dir.startsWith(File.separator)) {
							dir = File.separator+dir;
						}//以上代码得出   如: /file
						ftpClient.makeDirectory(dir);  //在ftp服务器创建文件夹
					} catch (Exception e) {
					}
				}
				String[] oldFiles= oldFile.list();
				for (String file : oldFiles) {
					copyFolder(realPath,new File(oldFile,file), ftpClient);
				}
			}else{
				//得到从项目名开始的子目录
				String dir = oldFile.toString().replace(realPath,"");     //如:  file\a.txt
				dir = dir.substring(0,dir.indexOf(oldFile.getName())-1);  //如: file
				if (!dir.startsWith(File.separator)) {
					dir = File.separator+dir;
				}
				try {
					ftpClient.makeDirectory(dir);  //在ftp服务器创建文件夹
					ftpClient.changeDirectory(dir); //把远程系统上的目录切换到参数dir所指定的目录  
				} catch (Exception e) {
					ftpClient.changeDirectory(dir); //把远程系统上的目录切换到参数dir所指定的目录  
				}
				InputStream in = new FileInputStream(oldFile);
				ftpClient.putFile(oldFile.getName(), in); //把文件输出到ftp服务器上
				in.close();
			}
		} 
		catch (Exception e) { 
			System.out.println("复制整个文件夹内容操作出错"); 
			e.printStackTrace(); 
		}
		return true; 
	}
	
	/** 
	 * 连接ftp服务器
	 * @param ip:FTP服务器的IP地址
	 * @param user:port:端口号
	 * @param user:登录FTP服务器的用户名
	 * @param password:登录FTP服务器的用户名的口令
	 * @param path:把远程系统上的目录切换到参数path所指定的目录   
	 * @return FtpClient 
	 */ 
	public static FtpClient connectServer(String ip, int port, String user,
			String password, String path) throws FtpProtocolException, IOException {  
		FtpClient ftpClient = FtpClient.create();       
		SocketAddress addr = new InetSocketAddress(ip,port);        
		ftpClient.connect(addr);              
		ftpClient.login(user, password.toCharArray());   
		if (path.length() != 0){                       
			//把远程系统上的目录切换到参数path所指定的目录                   
			ftpClient.changeDirectory(path);       
		}        
		return ftpClient;
	}
	
	/** 
	 * 连接ftp服务器
	 * @param path:把远程系统上的目录切换到参数path所指定的目录   
	 * @return FtpClient 
	 */ 
	public static FtpClient connectServer(String path) throws FtpProtocolException, IOException { 
		//获取properties文件里配置的数据
		PropertyResourceBundle res = (PropertyResourceBundle) PropertyResourceBundle.getBundle("ftpUpload");
		String ip = res.getString("ftpUpload.ip");
		Integer port = Integer.valueOf(res.getString("ftpUpload.port"));
		String user = res.getString("ftpUpload.user");
		String password = res.getString("ftpUpload.password");
		
		FtpClient ftpClient = FtpClient.create();       
		SocketAddress addr = new InetSocketAddress(ip,port);        
		ftpClient.connect(addr);              
		ftpClient.login(user, password.toCharArray());   
		if (path.length() != 0){                       
			//把远程系统上的目录切换到参数path所指定的目录                   
			ftpClient.changeDirectory(path);       
		}        
		return ftpClient;
	}
}


/**
 * @author zyt
 * @version : 2017年2月22日
 */
public class UploadFileServiceImpl implements UploadFileService {  

	private FtpClient ftpClient = null;
	//将服务器中的文件上传到ftp服务器上
	public void upload(){ 
		try {
			// 连接ftp服务器
			ftpClient = FtpUtils.connectServer("");
			WebApplicationContext application = ContextLoader.getCurrentWebApplicationContext();
			String path = application.getServletContext().getRealPath("/");
			File oldFile = new File(path,"file");
			boolean flag = FtpUtils.copyFolder(path,oldFile, ftpClient);  //复制文件夹以及下面的所有内容到ftp服务器上
			deleteAllFile(oldFile,oldFile.getName());  //删除文件夹以及下面的所有内容
			System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"提交到ftp服务器中...");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftpClient != null) {
				try {
					ftpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	} 
	/**
	 * 删除文件夹以及下面的所有文件
	 * @param file 文件夹路径
	 * @param excludeFile 指定不需要删除的空文件夹
	 */
	public void deleteAllFile(File file,String excludeFile){
		try {
			if (!file.exists()) {
				System.out.println("UploadFileServiceImpl.deleteAllFile()找不到指定文件!");
				return;
			}
			if (file.isDirectory()) {
				String[] list = file.list();
				for (String file2 : list) {
					deleteAllFile(new File(file,file2),excludeFile);
				}
				//过滤不需要删除的空文件夹
				if (!file.getName().equals(excludeFile)) {
					file.delete();
				}
			}else{
				file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("删除文件夹以及下面的所有文件出错!");
		}
	}
} 

<!--=======================定义定时任务=====================================-->

	<bean id="methodInvokingJobDetail"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject">
			<bean class="cmcc.jx.ict.xsgj.upload.ftp.service.impl.UploadFileServiceImpl"/>
		</property>
		<property name="targetMethod" value="upload" />
		<property name="concurrent" value="false" /><!-- 作业不并发调度 -->
	</bean>
	
	<!--=======================定义定时任务的触发器====================================-->
	
	<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
	<property name="jobDetail" ref="methodInvokingJobDetail" />  
	<!-- 每天12:00运行一次 -->
	
		<property name="cronExpression" value="0 0 0 * * ?" />
	</bean> 
	
	<!--=======================定义触发器的调度工厂===================================-->

	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="cronTrigger" />
			</list>
		</property>
	</bean>

/**
 * 文件下载过滤器
 * @author zyt
 * @version : 2017年3月1日
 */
public class DownloadFilter implements Filter{

	FilterConfig filterConfig	= null;
	
	public void init(FilterConfig filterConfig) throws ServletException{
		this.filterConfig = filterConfig;
	}

	public void destroy(){
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		//得到当前页面的URI
		String uri = URLDecoder.decode(req.getRequestURI(),"UTF-8");	 // lnwqxsgj/file/abc1/1.xls
		//去除项目名
		uri = uri.replace(req.getContextPath(),"");			// /file/abc1/1.xls
		FtpClient ftpClient;
		//判断是否是以该字符串开头  如果是就进行过滤
		if (uri.startsWith("/file/")) {
			//得到该项目的路径
			String realPath = req.getServletContext().getRealPath("/");  //D:\tomcat7x64\tomcat7x64\webapps\lnwqxsgj\
			//拼接得到该请求文件的绝对路径
			File file = new File(realPath,uri);	//D:\tomcat7x64\tomcat7x64\webapps\lnwqxsgj\file\abc1\1.xls
			//判断是否存在
			if (!file.exists()) {
				System.out.println("服务器不存在!");
				try {
					//得到该文件对应ftp服务器目录
					String realPath2 = uri.substring(0,uri.lastIndexOf("/")); // /file/abc1
					//连接ftp服务器 并且把目录切换到所指定的目录 
					ftpClient = FtpUtils.connectServer(realPath2);
					//在ftp服务器上读取该文件
					ftpClient.getFile(file.getName(), response.getOutputStream());
					System.out.println("ftp服务器存在!");
					System.out.println(realPath2+":"+file.getName());
					return;
				} catch (Exception e) {
					System.out.println("ftp服务器不存在!");
				}
			}else{
				System.out.println("服务器存在!");
			}
		}
		chain.doFilter(req, resp);
	}
}

quartz定时任务重要jar包

http://pan.baidu.com/s/1jIoLVam

发布了9 篇原创文章 · 获赞 10 · 访问量 5933

猜你喜欢

转载自blog.csdn.net/zyt_java/article/details/59108201