`
Sev7en_jun
  • 浏览: 1213314 次
  • 性别: Icon_minigender_1
  • 来自: 广州
博客专栏
84184fc0-d0b6-3f7f-a3f0-4202acb3caf5
Apache CXF使用s...
浏览量:109927
社区版块
存档分类
最新评论

Socket使用之Ftp上传工具类

阅读更多

涉及jar包:jftp.jar,jftp-bin-0_70.jar,log4j.jar(见附件)

1,FtpBaseUtils.java,主要作用获取IP,Port,username,password等等公共配置信息

import java.io.File;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import org.apache.log4j.Logger;

import com.xxx.vo.FtpVO;

import cz.dhl.ftp.Ftp;
import cz.dhl.ftp.FtpConnect;

public class FtpBaseUtils {
	private static final Logger logger = Logger.getLogger(FtpUploadUtils.class);
	private static final FtpVO ftpVo = new FtpVO();
	static {
		ftpVo.setIp(PropertiesUtil.getValue("FTP.IP"));
		ftpVo.setPort(PropertiesUtil.getValue("FTP.PORT"));
		ftpVo.setUser(PropertiesUtil.getValue("FTP.USER"));
		ftpVo.setPassword(PropertiesUtil.getValue("FTP.PASSWORD"));
		ftpVo.setFtpDir(PropertiesUtil.getValue("FTP.DIR.TASKFile"));// ftp文件存放目录
		ftpVo.setLocalDir(FileUtils.getTaskFilePath());// 本地文件目录
	}

	public FtpBaseUtils() {
		super();
	}

	/**
	 * 取得ftp连接实例
	 * 
	 * @param ftpVo
	 *            ftp连接信息
	 * @return Ftp cz.dhl.ftp.Ftp实例
	 */
	protected static Ftp getFtpInstance(FtpVO ftpVo) {
		Ftp ftp = new Ftp();
		try {
			String ftpIp = ftpVo.getIp();
			String ftpUser = ftpVo.getUser();
			String ftpPsw = ftpVo.getPassword();
			Integer ftpPort = Integer.valueOf(ftpVo.getPort());

			logger.info("测试连接,ftp信息:" + ftpVo.toString());
			try {
				// 测试是否能连接ftp服务器,如果没有连接,返回失败信息
				Socket client = new Socket();
				System.out.println("ftp 连接开始..");
				SocketAddress addr = new InetSocketAddress(ftpIp, ftpPort);
				// 连接5秒后无法连接,返回失败信息
				client.connect(addr, 1500); // 超时时间为1.5秒
				System.out.println("ftp 断开连接..");
				client.close();
			} catch (Exception e) {
				// TODO: handle exception
				throw new Exception("ftp链接失败:" + e.getMessage());
			}

			/* connect & login to host */
			FtpConnect ftpConn = FtpConnect.newConnect("ftp://" + ftpIp);
			ftpConn.setUserName(ftpUser);
			ftpConn.setPassWord(ftpPsw);
			ftpConn.setPortNum(ftpPort);
			ftp.connect(ftpConn);
		} catch (Exception e) {
			ftp = null;
			logger.error("连接失败!", e);
		}
		return ftp;
	}

	/**
	 * 获取FTP配置信息:ip,port,上传目录。。。
	 * 
	 * @return FtpVO
	 */

	protected static FtpVO getFtpCommonConfigVO() {
		return ftpVo;
	}

	/**
	 * 删除文件
	 * 
	 * @param filePath
	 *            文件路径名
	 */
	protected boolean delFile(String filePath) {
		// TODO Auto-generated method stub
		try {
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			} else {
				return false;
			}
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println("删除文件失败:" + e.getMessage());
			return false;
		}
	}

}

  

2 ,FtpUploadUtils.java负责具体上传操作

入口:uploadFile(String fileName) filename包括可获取到的完整的路径及文件名,其方法说明见注释

执行上传操作:doFtpUploadFile

 

import org.apache.log4j.Logger;

import com.xxx.vo.FtpVO;

import cz.dhl.ftp.Ftp;
import cz.dhl.ftp.FtpFile;
import cz.dhl.io.CoFile;
import cz.dhl.io.CoLoad;
import cz.dhl.io.LocalFile;

public class FtpUploadUtils extends FtpBaseUtils {
	private static final Logger logger = Logger.getLogger(FtpUploadUtils.class);

	/**
	 * 上传文件到FTP服务 1.先上传到WEB服务器临时目录 2.从临时目录上传到FTP服务器 3.删除临时文件 :fileName:完整路径+文件名
	 * 
	 * @throws Exception
	 */
	public static String uploadFile(String fileName) {
		logger.info("##############################");
		logger.info("开始准备上传文件:" + fileName);
		FtpVO ftpVO = getFtpCommonConfigVO();// 获取公共配置信息:帐号,端口
		ftpVO.setFtpFileName(fileName);
		ftpVO.setLocalFileName(fileName);
		logger.info("获取ftp配置信息:" + JsonUtils.toJson(ftpVO, false));
		Ftp ftp = getFtpInstance(ftpVO);// 获取FTP实例
		String message = doFtpUploadFile(ftp, ftpVO);
		// 删除临时文件
		/*
		 * if (super.delFile(filePathName)) { logger.info("删除临时文件成功." +
		 * filePathName); } else { logger.warn("删除临时文件失败." + filePathName); }
		 */
		logger.info("########结束文件上传######");
		return message;
	}

	private static String doFtpUploadFile(Ftp ftp, FtpVO ftpVo) {
		logger.info("##### 【开始】文件上传。。。。");
		String ftpDir = ftpVo.getFtpDir();
		String ftpFileName = ftpVo.getFtpFileName();
		String localDir = ftpVo.getLocalDir();
		String localFileName = ftpVo.getLocalFileName();
		String message = localFileName + "上传成功!";
		try {
			if (ftp == null) {
				throw new Exception("ftp连接失败!FTP信息:" + ftpVo.toString());
			}

			CoFile tmpfile = new LocalFile(localDir + localFileName); // 本地文件
			if (!tmpfile.exists()) {// 检测本地文件是否存在
				logger.info("文件【" + localDir + localFileName + "】不存在");
				message = "###文件" + localDir + localFileName + "】不存在";
			}

			CoFile ftpFolder = new FtpFile(ftpDir, ftp); // 远程文件夹
			CoFile ftpFile = new FtpFile(ftpDir + ftpFileName, ftp); // 远程文件名

			if (!ftpFolder.exists()) {// 检测ftp目录是否存在
				ftpFolder.mkdir();
				logger.warn("folder is not exist:" + ftpDir);
			}
			// copy file to the other position
			logger.info(">>文件是否存在:" + ftpFile.exists());
			if (!ftpFile.exists()) {// 检测ftp文件是否存在
				if (!CoLoad.copy(ftpFile, tmpfile)) {
					logger.error("文件从web服务器上传到FTP服务器失败.FTP信息:"
							+ ftpVo.toString());
					message = localDir + localFileName
							+ "文件从web服务器上传到FTP服务器失败.FTP信息:" + ftpVo.toString();
				} else {
					message = localDir + localFileName + "文件上传成功";
					logger.info(message);
				}
			} else {
				message = localDir + localFileName + "已存在,上传失败! FTP信息:"
						+ ftpVo.toString();
				logger.warn(message);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			message = localDir + localFileName + "上传失败:" + e.getMessage();
		} finally {
			ftp.disconnect();
		}
		logger.info("上传返回信息:" + message);
		logger.info("##### 【结束】文件上传操作。。。。");
		return message;
	}
}

 

 

3,PropertiesUtil.java:负责配置文件加载(可选,去掉之后需要修改相应代码及配置)

 

import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * A simple base implementation of Properties file
 * 
 * @author Eagles 2005-12-22
 */
public final class PropertiesUtil {
	protected static Logger logger = Logger.getLogger(PropertiesUtil.class);

	/**
	 * 配置文件名称
	 */
	private static final String FILENAME = "config.properties";
	private static Properties prop = null;

	/**
	 * 初始化加载配置文件
	 * 
	 * @return:an instance from Properties
	 */
	private static synchronized Properties getProperties() {
		logger.debug("init an instance from the Properties");
		if (prop == null) {
			prop = new Properties();
			try {
				prop.load(PropertiesUtil.class.getClassLoader()
						.getResourceAsStream(FILENAME));
				return prop;
			} catch (IOException ex) {
				logger.error("init an instance from the Properties error:"
						+ ex.getMessage());
				return null;
			}
		}
		return prop;
	}

	public static String getValue(String param) {
		String result = getProperties().getProperty(param);
		return result == null ? "" : result;
	}

	public static void main(String[] args) {
		System.out.println(PropertiesUtil.getValue("ftpPassword"));
	}

}

 

 对应加载的配置文件

 

#----------------------------------------------
# Ftp Config
#----------------------------------------------
FTP.IP=192.168.7.161
FTP.USER=root
FTP.PASSWORD=etone
FTP.PORT=21
#ftp存放目录
FTP.DIR.TASKFile=/data/
#本地文件存放目录
LOCAL.DIR.TEMP.TASKFile=/temp/
 

存放ftp配置属性VO(可选,去掉之后需要修改相应代码及配置)

 

import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * ftp相关数据封装类
 * @author Administrator
 *
 */
public class FtpVO {
	
	private String ip;
	private int port;
	private String user;
	private String password;
	private String ftpDir;
	private String ftpFileName;
	
	private String localDir;
	private String localFileName;
	
	private boolean isDelOldFile;
	private boolean isReName;
	
	public String getFtpDir() {
		return ftpDir;
	}
	public void setFtpDir(String ftpDir) {
		this.ftpDir = ftpDir;
	}
	public String getFtpFileName() {
		return ftpFileName;
	}
	public void setFtpFileName(String ftpFileName) {
		this.ftpFileName = ftpFileName;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public boolean isDelOldFile() {
		return isDelOldFile;
	}
	public void setDelOldFile(boolean isDelOldFile) {
		this.isDelOldFile = isDelOldFile;
	}
	public boolean isReName() {
		return isReName;
	}
	public void setReName(boolean isReName) {
		this.isReName = isReName;
	}
	public String getLocalDir() {
		return localDir;
	}
	public void setLocalDir(String localDir) {
		this.localDir = localDir;
	}
	public String getLocalFileName() {
		return localFileName;
	}
	public void setLocalFileName(String localFileName) {
		this.localFileName = localFileName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}

	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}


}
 

4,FileUtils.java辅助类(可选,可以把此部分代码移到FtpBaseUtils.java中,writeToFile()可删掉

 

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

public class FileUtils {
	private static final Logger logger = Logger.getLogger(FileUtils.class);

	public static final String taskFilePath = PropertiesUtil
			.getValue("LOCAL.DIR.TEMP.TASKFile");
	public static final String prefix = "test_";
	public static final String suffix = ".txt";
	public static String webRoot = "";
	static {
		// 获取webRoot目录
		webRoot = FileUtils.class.getClassLoader().getResource("").toString();// file:/D:/publish/Elvis_GZ_V4/WEB-INF/classes/
		if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {
			webRoot = webRoot.replace("file:/", "");// file:/D:/publish/Elvis_GZ_V4/WEB-INF/classes/
		} else {
			webRoot = webRoot.replace("file:", "");// file:/opt/web/Elvis_GZ_V4/WEB-INF/classes/
		}
		webRoot = webRoot.replace("/WEB-INF/classes/", "");
		webRoot = webRoot.replace("%20", " ");
	}

	public static final String getWebRoot() {
		return webRoot;
	}

	public static final String getTaskFilePath() {
		return getWebRoot() + taskFilePath;
	}

	/**
	 * 内容写入指定文件
	 * 
	 * @param content
	 * @param fileName
	 */
	public static void writeToFile(String content, String fileName) {
		System.out.println("sssss");
		BufferedWriter buffWriter = null;
		try {
			buffWriter = new BufferedWriter(new FileWriter(fileName, true));
			buffWriter.write(content);
			buffWriter.newLine();
		} catch (IOException e) {
			logger.error("写入文件【" + fileName + "】失败:" + e.getMessage(), e);
		} finally {
			if (null != buffWriter) {
				try {
					buffWriter.flush();
					buffWriter.close();
				} catch (IOException e) {
					logger.error("close bufferWriter failed:" + e.getMessage(),
							e);
				}

			}
			System.out.println("eeeee");
		}
	}
}
 

 

 

0
0
分享到:
评论

相关推荐

    java工具类 ftp 文件比较 socket http

    java工具类 ftp 文件比较 socket http

    c#实现ftp工具类

    这是使用c#实现FTP功能的工具类,包含socket技术。

    基于SpringMVC的一个web框架

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    soketFTP核心类

    .net ftp工具类 采用socket技术实现ftp命令 传输稳定 支持断点续传

    一个可以直接运行的基于SpringMVC的web框架1.1.12

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    可以直接运行的基于SpringMVC的web框架示例,也可以直接当公司框架

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    Unix下的FTP客户端

    并且无法获知出错的错误代码,用C++封装成一个工具类后,任何项目都可以重用了。 操作很方便,就像平常的FTP操作: 1:登陆FTP服务端 FTPTools ftpTools (conts string &pm_sFtpServer,int pm_iFtpPort); ...

    基于Spring MVC的web框架 1.1.11

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    SpringMVC基础上的web框架

    版本管理,服务根路径工具类,文件上传工具类 1.0.10 集成ueditor在线编辑器 1.0.11 地址联动 1.0.12 Excel工具类 Word工具类 Java NIO实现socket工具类 分布式session jdk升级到1.7 嵌入式redis服务(只支持linux) ...

    文件的上传和下载帮助类C#实现

    3. 文件传输协议(FTP):使用专门设计的FTP客户端软件或命令行工具,通过FTP协议连接到FTP服务器,将本地文件上传到服务器指定目录。 4. 基于Socket编程:编写客户端和服务器端代码,通过Socket建立连接,然后传输...

    util:J2EE日常开发中整理的工具类。分为IO类扩展、image类扩展、JDK常用类扩展、网络类扩展等

    V1.8.9更新日志: 1.ftp工具类增加上传文件功能。 2.邮件增加抄送、密送、发送附件功能。 3.读取配置文件工具类增加修改和新增属性功能。 4.其他6处代码优化。 老沙超级工具包-包含几十个工具类,经历了5年的认真...

    S-FTPClient(Swing,Java,Socket,FTP,加密算法).zip

    Java是一种广泛使用的面向对象的编程语言,由Sun ...综上所述,Java凭借其强大的特性和广泛的适用范围,在企业级应用、互联网服务、移动开发等领域均扮演着举足轻重的角色,是现代软件开发不可或缺的重要工具之一。

    前端-后端java的Util类的工具类

    ├─28个java常用的工具类 │ │ Base64.java │ │ Base64DecodingException.java │ │ CConst.java │ │ CharTools.java │ │ ConfigHelper.java │ │ Counter.java │ │ CTool.java │ │ DateHandler.java ...

    Visual C++6.0网络编程技术

    第四章 Casync Socket类和CSocket类 60 4.1 Casync Socket类 60 4.2 Csocket类 61 第五章 Winsock库函数参考 66 5.1 Windows Socket 1.1 库函数参考 66 5.2 数据库函数 72 5.3 Windows扩展函数 74 5.4 Windows ...

    最新Python3.5零基础+高级+完整项目(28周全)培训视频学习资料

    Sublime Text工具使用介绍 谢幕 第17周 今日内容概要 jQuery 和Dom关系及jQuery版本 jQuery选择器 实例多选反选取消 删选器以及Tab菜单示例 示例:模态编程框 jQuery 样式以及属性操作 示例:TAB切换菜单 jQuery...

    Delphi网络通信协议分析与应用实现pdf清晰

    3.3 使用Windows内置FTP程序 3.4 深入FTP协议 3.4.1 FTP命令大全 3.4.2 FTP工作模式 3.5 开发FTP程序的方法 3.6 API开发高级FTP客户端程序 3.6.1 建立工程项目 3.6.2 关键代码分析 3.7 开发FTP服务器 3.7.1...

    Java典型模块

    26.2.1 FTP服务器操作的工具类 26.2.2 实现文件上传的类 26.2.3 实现文件下载的类 26.3 知识点扩展——FtpClient类的相关知识 26.3.1 实现FTP服务器相关操作类 26.3.2 相关JAR包导入问题 26.4 小结 第27章 Web服务器...

    python入门到高级全栈工程师培训 第3期 附课件代码

    05 FTP之文件上传 06 FTP之断点续传 08 FTP之进度条 09 FTP之cd切换 11 FTP之创建文件夹及MD5校验思路 第33章 01 操作系统历史 02 进程的概念 03 线程的概念 04 线程的调用以及join方法 05 setDaemon方法和继承式...

Global site tag (gtag.js) - Google Analytics