nedrukxhxl 发表于 2016-6-9 04:18:43

common-net ftp封装

public class FTPSystem {
private FTPClient client = new FTPClient();
private int port;
private String ip;
private String user;
private String pw;
private String dirId;
private LogFactory log = LogFactory.getLog();
private boolean preConn = false;
public FTPSystem(String ip,String user,String pw,int port){
this.port = port;
this.ip = ip;
this.user = user;
this.pw = pw;
if(connect()){
preConn = true;
}
}
/**
*
* 连接服务器
*
* @return
* @author      YitianC
* @history
*            YitianC Oct 28, 2011 5:13:43 PM
*/
public boolean connect() {
synchronized(this){
if(client.isConnected()){
preConn = true;
return true;
}
long startTime = System.currentTimeMillis();
try {
client.setTimeOut(2000);
client.connect(ip, port);
client.login(user, pw);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
return false;
}
preConn = true;
return true;
}catch (Exception e) {
log.printException(null, e);
}
finally{
log.debug("FTP connection cost time "+(float)(System.currentTimeMillis()-startTime)/1000+" seconds.");
}
return false;
}
}
public void test(){
FTPFile[] fs = null;
try {
//fs = this.getFiles(new String("/home/root/listenerDebug/十大二".getBytes("gbk"),"iso-8859-1"));
fs = this.getFiles("/home/root/listenerDebug/十大二");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for(FTPFile f:fs){
try {
System.out.println(new String(f.getName().getBytes("iso-8859-1"),"gbk"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
System.out.println(this.isExist("/home/root/listenerDebug/flex配置文档1.docx"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*try {
this.put("d:/listenerDebug/normal/flex配置文档1.docx", "/home/root/listenerDebug");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//this.get("/home/root/listenerDebug/flex配置文档1.docx", "d:/listenerDebug/normal/flex配置文档1.docx");
}
/**
*
* 上传
*
* @param localPath
* @param remotePath
* @return
* @author      YitianC
* @history
*            YitianC Oct 26, 2011 12:28:28 PM
*/
public boolean put(String localPath,String remotePath)throws Exception{
synchronized(this){
if(localPath==null || remotePath==null)
return false;
File localFile = new File(localPath);
if(!localFile.exists()) return false;
if(!preConn)return false;
if(!connect()){
return false;
}
if(!mkdir(remotePath)){
System.out.println("无法建立目录 "+remotePath);
return false;
}
String fileName = localFile.getName();
try{
fileName = new String(fileName.getBytes("gbk"),"iso-8859-1");
}catch(Exception e){
}
String remoteFile = DirUtil.dirAddFileName(remotePath, fileName);
DataInputStream dis =null;;
try {
client.setFileType(FTPClient.BINARY_FILE_TYPE);// 必须是二进制类型,不然会导致错误
dis= new DataInputStream(new FileInputStream(localFile));
return client.storeFile(remoteFile, dis);
} catch (IOException e) {
log.printException(null, e);
}
finally{
if(dis!=null){
dis.close();
}
}
return false;
}
}
/**
*
* 下载
*
* @param remoteName
* @param localPath
* @return
* @author      YitianC
* @history
*            YitianC Oct 26, 2011 12:28:35 PM
*/
public boolean get(String remoteName,String localPath){
synchronized(this){
if(!preConn)return false;
if(!connect()) return false;
// 分段读取
DataOutputStream os = null;
try {
client.setFileType(FTPClient.BINARY_FILE_TYPE);// 必须是二进制类型,不然会导致错误
os = new DataOutputStream(new FileOutputStream(localPath));
return client.retrieveFile(remoteName, os);
} catch (Exception e) {
e.printStackTrace();
log.printException(null, e);
return false;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.printException(null, e);
}
}
}
}
}
/**
*
* 根据文件名取得文件大小
*
* @param name文件名
* @return
* @author      YitianC
* @history
*            YitianC Oct 28, 2011 5:14:33 PM
*/
public long getFileSize(String name){
FTPFile file = this.getFile(name);
if(file == null) return 0;
return file.getSize();
}
/**
*
* 取得文件的详细信息
*
* @param path 文件路径
* @return
* @author      YitianC
* @history
*            YitianC Oct 28, 2011 5:15:03 PM
*/
public FTPFile getFile(String path){
synchronized(this){
if(!preConn)return null;
if(!connect()) return null;
FTPFile[] f;
try{
path = new String(path.getBytes("gbk"),"iso-8859-1");
}catch(Exception e){
}
try {
f = client.listFiles(path);
} catch (Exception e) {
log.printException(null, e);
return null;
}
if(f==null){
return null;
}
else if(f.length==0){
return null;
}
FTPFile file = f;
f = null;
return file;
}
}
/**
*
* 进入FTP目录 相当于cd命令
*
* @param path
* @return
* @author      YitianC
* @history
*            YitianC Oct 28, 2011 5:16:22 PM
*/
public boolean cd(String path){
synchronized(this){
try {
if(!preConn)return false;
return client.changeWorkingDirectory(path);
} catch (IOException e) {
log.printException(null, e);
}
return false;
}
}
/**
*
* 判断文件或路径是否存在
*
* @param path
* @return
* @author      YitianC
* @history
*            YitianC Oct 28, 2011 5:16:47 PM
*/
public boolean isExist(String path){
synchronized(this){
if(!preConn)return false;
FTPFile[] f;
String fileName = DirUtil.getLastPathName(path);
try{
fileName = new String(fileName.getBytes("gbk"),"iso-8859-1");
}catch(Exception e){
}
try {
f = client.listFiles(DirUtil.getParentPath(path));
if(f!=null){
for(FTPFile ff:f){
if(ff.getName().equals(fileName)){
return true;
}
}
}
} catch (Exception e) {
log.printException(null, e);
return false;
}
return false;
}
}
/**
*
* 取得path目录下的文件列表
*
* @param path
* @return
* @author      YitianC
* @history
*            YitianC Oct 28, 2011 5:17:06 PM
*/
public FTPFile[] getFiles(String path){
synchronized(this){
if(!preConn)return null;
if(!connect()) return null;
try{
path = new String(path.getBytes("gbk"),"iso-8859-1");
}
catch(Exception e){
}
try {
return client.listFiles(path);
} catch (IOException e) {
log.printException(null, e);
}
return null;
}
}
/**
*
* 移动文件
*
* @param path原路径
* @param newPath新路径
* @return
* @author      YitianC
* @history
*            YitianC Oct 28, 2011 5:17:22 PM
*/
public boolean move(String path,String newPath){
synchronized(this){
if(!preConn)return false;
if(!connect())return false;
try {
return client.rename(path, newPath);
} catch (IOException e) {
log.printException(null, e);
}
return false;
}
}
public void printFiles(FTPFile[] files){
synchronized(this){
if(files==null) return;
for(FTPFile f:files){
log.debug("name="+f.getName());
}
}
}
/**
*
* 建立目录
*
* @param path
* @return
* @author      YitianC
* @history
*            YitianC Oct 28, 2011 5:18:01 PM
*/
public boolean mkdir(String path){
synchronized(this){
if(!preConn)return false;
if(!connect())return false;
if(this.isExist(path))return true;
path = this.getEncodePath(path);
try {
return mkd(path);
} catch (Exception e) {
log.printException(null, e);
return false;
}
}
}
public boolean mkd(String path)throws Exception{
synchronized(this){
if(!preConn)return false;
if(!connect())return false;
if(!this.isExist(path)){
if(!mkd(DirUtil.getParentPath(path))){
return false;
}
int rt = client.mkd(path);
if(this.isExist(path)){
return true;
}
return false;
}
return true;
}
}
/**
*
* 断开连接
*
* @return
* @author      YitianC
* @history
*            YitianC Oct 28, 2011 5:18:19 PM
*/
public boolean disConnect(){
synchronized(this){
if(!preConn)return true;
if(client.isConnected()){
try {
client.disconnect();
return true;
} catch (IOException e) {
log.printException(null, e);
return false;
}
}
return true;
}
}
public String getEncodePath(String path){
try {
String npath = new String(path.getBytes("utf-8"),"iso-8859-1");
path = npath;
} catch (UnsupportedEncodingException e1) {
log.printException(null, e1);
}catch(Exception e){
log.printException(null, e);
}
return path;
}
public boolean rmDir(String path){
synchronized(this){
try{
if(!preConn)return false;
path = this.getEncodePath(path);
client.rmd(path);
}catch(Exception e){
log.printException(null, e);
return false;
}
}
return !this.isExist(path);
}
public boolean rmEmptyDir(String path){
try{
String paDir = DirUtil.getParentPath(path);
FTPFile f [] = this.getFiles(path);
if(f == null){
return true;
}
else if(f.length==0){
return true;
}
else if(f.length==2){
String name1 = f.getName();
String name2 = f.getName();
if(name2==null||name1==null){
return false;
}
else{
if((name2.equals(".")&&name1.equals(".."))||(name1.equals(".")&&name2.equals(".."))){
if(!this.rmDir(path)){
return false;
}
else {
return rmEmptyDir(paDir);
}
}
else{
return false;
}
}
}
}catch(Exception e){
log.printException(null, e);
}
return false;
}
public void release(){
if(disConnect()){
client = null;
}
}
public static void main(String[] args){
FTPSystem f = new FTPSystem("172.19.201.200","weblogic","web123",21);
f.test();
}
public String getDirId() {
return dirId;
}
public void setDirId(String dirId) {
this.dirId = dirId;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public boolean isPreConn() {
return preConn;
}
public void setPreConn(boolean preConn) {
this.preConn = preConn;
}
}
  
  好像这个版本的不支持设置连接超时,所以重写了个
  

class FTPClient extends org.apache.commons.net.ftp.FTPClient{
private SocketFactory _socketFactory_=SocketFactory.getDefault();
private int timeOut = 2000;
public FTPClient(){
}
public void connect(InetAddress host, int port)
throws SocketException, IOException
{
_socket_=this._socketFactory_.createSocket();
_socket_.connect(new InetSocketAddress(host, port), timeOut);
_connectAction_();
}
public void connect(String hostname, int port)
throws SocketException, IOException
{
connect(InetAddress.getByName(hostname), port);
}
public void setConnTimeOut(int timeOut){
}
public int getTimeOut() {
return timeOut;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
}

  
页: [1]
查看完整版本: common-net ftp封装