实现
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import com.ctid.core.exception.ServiceException;
import com.ctid.mainlib.system.util.datehandle.PathHandler;
public class FtpHandle implements AutoCloseable{
private static final Log Log = LogFactory.getLog(FtpHandle.class);
private FTPClient ftpClient;
public FtpHandle(String host, int port, String username, String password, int timeout) throws Exception {
super();
this.ftpClient = new FTPClient();
this.ftpClient.setBufferSize(8192);
this.ftpClient.setConnectTimeout(timeout);
this.ftpClient.connect(host, port);
this.ftpClient.setDataTimeout(timeout);
this.ftpClient.setSoTimeout(timeout);
if(!FTPReply.isPositiveCompletion(this.ftpClient.getReplyCode())){
this.ftpClient.disconnect();
throw new ServiceException("创建FTP连接失败, 返回码: " + this.ftpClient.getReplyCode());
}
if(!this.ftpClient.login(username, password)){
this.ftpClient.disconnect();
throw new ServiceException("创建FTP连接失败, 登录失败!");
}
this.ftpClient.enterLocalPassiveMode();
}
public List<String> getFileNameList(String folder) throws ServiceException{
try {
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
List<FTPFile> ftpFileList = Arrays.asList(this.ftpClient.listFiles(folder));
ArrayList<String> fileNameList = new ArrayList<String>();
ftpFileList.forEach(ftpFile -> fileNameList.add(ftpFile.getName()));
return fileNameList;
} catch (IOException e) {
throw new ServiceException("获取指定文件夹下的文件名称集合执行异常, " + e.toString());
}
}
public boolean isFile(String path) throws ServiceException{
try {
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
FTPFile[] files = this.ftpClient.listFiles(path);
return files != null && files.length > 0;
} catch (IOException e) {
return false;
}
}
public boolean isDire(String directory){
try {
return this.ftpClient.changeWorkingDirectory(directory);
} catch (IOException e) {
return false;
}
}
public boolean fileImport(String ftpPath, String localPath) throws ServiceException{
File file = PathHandler.initPath(localPath);
try(FileOutputStream out = new FileOutputStream(file, true)) {
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
FTPFile[] ftpFiles = this.ftpClient.listFiles(ftpPath);
if(ftpFiles == null || ftpFiles.length != 1){
throw new ServiceException("FTP文件导出执行异常, 读取文件异常");
}
if (file.length() >= ftpFiles[0].getSize()) {
return false;
}
if(file.length() > 0){
this.ftpClient.setRestartOffset(file.length());
}
return this.ftpClient.retrieveFile(ftpPath, out);
} catch (Exception e) {
Log.error("将FTP文件导入到本地执行异常, 异常信息: " + e.toString());
return false;
}
}
public boolean fileExport(String ftpPath, String localPath) throws ServiceException {
try {
this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
String fileName = ftpPath.substring(ftpPath.lastIndexOf("/") + 1);
String directory = ftpPath.substring(0, ftpPath.lastIndexOf("/") + 1);
initPath(directory);
FTPFile[] files = ftpClient.listFiles(ftpPath);
if(files.length > 0 && files[0].getSize() >= new File(localPath).length()){
this.ftpClient.deleteFile(fileName);
}
InputStream inputStream = new FileInputStream(localPath);
return this.ftpClient.storeFile(fileName, inputStream);
} catch (Exception e) {
return false;
}
}
public boolean initPath(String directory) throws ServiceException {
try {
if (ftpClient.changeWorkingDirectory(directory)) {
return true;
}
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
this.ftpClient.changeWorkingDirectory(File.separator);
String[] directorys = directory.split("/");
for (String dir : directorys) {
if(!ftpClient.changeWorkingDirectory(dir)){
if(this.ftpClient.makeDirectory(dir)){
ftpClient.changeWorkingDirectory(dir);
}
}
}
return true;
} catch (Exception e) {
throw new ServiceException("初始化FTP目录执行异常, " + e.toString());
}
}
public boolean refileName(String srcPath, String targetPath) throws ServiceException {
try {
return ftpClient.rename(srcPath, targetPath);
} catch (Exception e) {
throw new ServiceException("移动文件, 或者重命名文件执行异常, " + e.toString());
}
}
public void rootPath() throws ServiceException{
try {
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
this.ftpClient.changeWorkingDirectory(File.separator);
} catch (IOException e) {
throw new ServiceException("切换到FTP根目录执行异常, " + e.toString());
}
}
@Override public void close(){
try {
if(this.ftpClient != null) {
this.ftpClient.logout();
}
if(this.ftpClient != null && this.ftpClient.isConnected()) {
this.ftpClient.disconnect();
}
} catch (IOException e) {
Log.error("关闭FTP连接执行异常, 异常信息: " + e.toString());
}
}
}
使用
public static void main(String[] args) {
String host = "172.18.2.239";
int port = 22;
String username = "CTCC";
String password = "**************";
int timeout = 10000;
try(FtpHandle ftpHandle = new FtpHandle(host , port, username, password, timeout)) {
ftpHandle.fileExport("FTP路径", "本地路径");
ftpHandle.fileImport("FTP路径", "本地路径");
} catch (Exception e) {
e.printStackTrace();
}
}