ftp工具类

package com.zq.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;

/**
*
* Ftp操作工具类,依赖:org.apache.commons.net_2.2.0.v201101241833.jar
*
* Created by MyEclipse. Author: ChenBin E-mail: chenbin_2008@126.com Date:
* 2016-11-3 Time: 下午7:08:10
*/
public class FtpUtils {
private static Logger log = Logger.getLogger(FtpUtils.class);
private static FTPClient ftpClient = null;

public static void main(String[] args) {
/*
* FtpUtils.init(Config.FTP_ENCODING, Config.FTP_SERVER_IP,
* Config.FTP_USERNAME, Config.FTP_PASSWORD, Config.FTP_SERVER_PORT);
* System.out.println(isDirExist("/test1")); FtpUtils.delDir("/test");
* System.out.println(FtpUtils.delFile("/test.txt"));
* FtpUtils.rename("/test.txt", "test1.txt"); String newPath =
* "/test2/1/2"; FtpUtils.createDir(newPath);
* FtpUtils.changeToPath(newPath); FtpUtils.createDir("newDir");
* FtpUtils.uploadFile("F:\yycpjmb.xls", "yys.xls");
* FtpUtils.changeToPath("test1\"); FtpUtils.delDir("\a\");
* FtpUtils.logout();
* FtpUtils.download("system\windowsapp\2017\03\",
* "WDS_17-03-01_1488364296111_ECkoQI.rar", "D:\test.rar");
*/
}

/**
* Description : 初始化ftp服务器客户端
*
* @author : ChenBin
* @date : 2016年12月5日 下午5:04:23
*/
public static void init(String ftpEncoding, String ftpServerIp, String uName, String pwd, int port) {
if (ftpClient == null)
ftpClient = new FTPClient();
if (!ftpClient.isConnected()) {
try {
log.info("连接FTP服务器");
ftpClient.setControlEncoding(ftpEncoding);
ftpClient.connect(ftpServerIp);
ftpClient.login(uName, pwd);
ftpClient.setDefaultPort(port);
// ftp服务器回复值
int replyCode = ftpClient.getReplyCode();
ftpClient.setDataTimeout(120000);
log.info("FTP服务器连接成功,状态码:"+replyCode);
} catch (SocketException e) {
e.printStackTrace();
System.err.println("登录ftp服务器失败,连接超时!");
log.debug("登录ftp服务器失败");
} catch (IOException e) {
e.printStackTrace();
System.err.println("登录ftp服务器失败,FTP服务器无法打开!");
log.debug("登录ftp服务器失败");
}

}
}

/**
* 更改当前FTP会话的工作目录
*
* @param path:
* a/b/c
* @return
*/
public static boolean changeToPath(String path) {
try {
return ftpClient.changeWorkingDirectory(path);
} catch (IOException e) {
log.error("change working derectory failed: " + e.toString());
e.printStackTrace();
return false;
}
}

/**
* Description :将文件流输出至ftp服务器,如果ftp目录下已经存在同名文件将会被覆盖
*
* @author : ChenBin
* @throws IOException
* @date : 2016年12月5日 下午9:43:42
*/
public static boolean uploadFile(FileInputStream fileStream, String remoteFileName) throws IOException {
return ftpClient.storeFile(remoteFileName, fileStream);
}

/**
* Description : 将文件对象输出至ftp服务器,如果ftp目录下已经存在同名文件将会被覆盖
*
* @author : ChenBin
* @date : 2016年12月5日 下午9:44:06
*/
public static boolean uploadFile(File currentFile, String remoteFileName) {
FileInputStream bis = null;
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
bis = new FileInputStream(currentFile);
return uploadFile(bis, remoteFileName);
} catch (Exception e) {
e.printStackTrace();
log.debug("file upload " + currentFile.getPath() + " failed: " + e.toString());
return false;
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
log.error("FileInputStream close fail:" + e.toString());
e.printStackTrace();
}
}
}

/**
* Description : 上传一个指定的本地文件路径至ftp服务器当前工作目录,如果ftp目录下已经存在同名文件将会被覆盖
*
* @author : ChenBin
* @date : 2016年12月5日 下午9:41:56
* @param :
* filePath-文件在本地的路径;remoteFileName-上传至ftp服务器的文件名
*/
public static boolean uploadFile(String currentFilePath, String remoteFileName) {
File currntFile = new File(currentFilePath);
if (currntFile.exists()) {
return uploadFile(currntFile, remoteFileName);
} else {
log.error("file: " + currentFilePath + "is not exists!");
return false;
}
}

/**
* Description : 在ftp服务器上创建一个目录,如:a/b/c
*
* @author : ChenBin
* @date : 2016年12月5日 下午5:04:35
*/
public static boolean createDir(String path) {
try {
return ftpClient.makeDirectory(path);
} catch (IOException e) {
log.debug("create directory failed: " + e.toString());
e.printStackTrace();
return false;
}
}

/**
* Description : 重命名远程文件/文件夹
*
* @author : ChenBin
* @date : 2016年12月5日 下午9:35:58
*/
public static boolean rename(String name, String toName) {
try {
return ftpClient.rename(name, toName);
} catch (IOException e) {
log.error("rename ftp file/dir name failed: " + e.toString());
e.printStackTrace();
return false;
}
}

/**
* Description : 删除ftp服务器上的文件夹
*
* @author : ChenBin
* @date : 2016年12月5日 下午9:12:35
*/
public static boolean delDir(String dirPath) {
try {
return ftpClient.removeDirectory(dirPath);
} catch (IOException e) {
log.error("remove directory :" + dirPath + "failed,reson:" + e.toString());
e.printStackTrace();
return false;
}
}

/**
* Description : 删除ftp服务器上的文件
*
* @author : ChenBin
* @date : 2016年12月5日 下午9:18:14
* @return true-删除ftp文件成功;false-删除ftp文件失败
*/
public static boolean delFile(String filePaht) {
try {
return ftpClient.deleteFile(filePaht);
} catch (IOException e) {
log.error("delete file failed: " + e.toString());
e.printStackTrace();
return false;
}
}

/**
* Description : 检查文件夹是否存在(通过判断更改当前的工作目录是否成功来确定文件夹是否存在)
*
* @author : ChenBin
* @date : 2016年12月5日 下午5:07:06
*/
public static boolean isDirExist(String dir) {
try {
// 获取当前的工作目录
String currentDirectory = ftpClient.printWorkingDirectory();
boolean isExist = ftpClient.changeWorkingDirectory(dir);
// 切换回之前的工作目录
ftpClient.changeWorkingDirectory(currentDirectory);
return isExist;
} catch (IOException e) {
log.error("check ftp dir exist failed: " + e.toString());
e.printStackTrace();
return false;
}
}

/**
* Description : 断开ftp登录
*
* @author : ChenBin
* @date : 2016年12月5日 下午4:53:46
*/
public static void logout() {
try {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
log.debug("ftp server logout! isConnected:" + ftpClient.isConnected());
log.debug("FTP服务器断开连接");
}
} catch (Exception e) {
log.error("ftp logout failed:" + e.toString());
e.printStackTrace();
}
}

public static void download(String remotePath, String remoteFileName, String localPath) {
BufferedOutputStream outStream = null;
try {
log.info("从FTP服务器开始下载文件");
ftpClient.changeWorkingDirectory(remotePath);
outStream = new BufferedOutputStream(new FileOutputStream(localPath));
ftpClient.retrieveFile(remoteFileName, outStream);
log.info("从FTP服务器下载文件结束");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

/**
* 复制单个文件
*
* @param oldPath
* String 原文件路径 如:c:/fqf.txt
* @param newPath
* String 复制后路径 如:f:/fqf.txt
* @return boolean
*/
public static void copyFile(String oldPath, String newPath) {
InputStream inStream = null;
FileOutputStream fs = null;
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);

if (oldfile.exists()) { // 文件存在时
inStream = new FileInputStream(oldPath); // 读入原文件
fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
// int length = 0;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}

}
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
} finally {
try {
inStream.close();
fs.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
}

原文地址:https://www.cnblogs.com/rey888/p/8315944.html