当前位置 博文首页 > 昵称已经被占用咯:FTPUtil网上查找稍作修改方便以后使用
###工具类
package xxx.ftporsftpconfig;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.lang3.StringUtils;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* FTP工具类
*
* @author zhangzz
*
*/
public class FtpUtil {
private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);
/**
* 获取FTPClient对象
*
* @param hostname FTP主机服务器
* @param password FTP 登录密码
* @param username FTP登录用户名
* @param port FTP端口 默认为21
* @return
*/
public static FTPClient getFTPClient(FtpOrSftpConfig sftpConfig) {
FTPClient client = null;
try {
client = new FTPClient();
if (!client.isConnected()) {
client.connect(sftpConfig.getHostname(), sftpConfig.getPort());// 连接FTP服务器
client.login(sftpConfig.getUsername(), sftpConfig.getPassword());// 登陆FTP服务器
}
if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
System.out.println("未连接到FTP,用户名或密码错误。");
client.disconnect();
} else {
System.out.println("FTP连接成功。");
}
} catch (SocketException e) {
e.printStackTrace();
System.out.println("FTP的IP地址可能错误,请正确配置。");
} catch (IOException e) {
e.printStackTrace();
System.out.println("FTP的端口错误,请正确配置。");
}
return client;
}
/*
* 从FTP服务器下载文件
*
* @param hostname FTP IP地址
*
* @param username FTP 用户名
*
* @param password FTP用户名密码
*
* @param port FTP端口
*
* @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
*
* @param localPath 下载到本地的位置 格式:H:/download
*
* @param fileName 文件名称
*/
public static boolean downloadFtpFile(String localPath, String fileName, FtpOrSftpConfig sftpConfig) {
FTPClient client = null;
OutputStream out = null;
boolean flag = false;
try {
client = getFTPClient(sftpConfig);
client.setControlEncoding("UTF-8"); // 中文支持
client.setFileType(FTPClient.BINARY_FILE_TYPE);
client.enterLocalPassiveMode();
client.changeWorkingDirectory(sftpConfig.getFilePath());
File localFile = new File(localPath + File.separatorChar + fileName);
out = new FileOutputStream(localFile);
// 下载文件
flag = client.retrieveFile(fileName, out);
client.logout();
} catch (FileNotFoundException e) {
System.out.println("没有找到" + sftpConfig.getFilePath() + "文件");
e.printStackTrace();
} catch (SocketException e) {
System.out.println("连接FTP失败。");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取错误。");
e.printStackTrace();
} finally {
close(client, out);
}
return flag;
}
/**
* 下载文件
*
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
* @param sftpConfig
* @return
*/
public static void download(String directory, String downloadFile, String saveFile, FtpOrSftpConfig sftpConfig) {
OutputStream output = null;
FTPClient client = null;
try {
File localDirFile = new File(saveFile);
// 判断本地目录是否存在,不存在需要新建各级目录
if (!localDirFile.exists()) {
localDirFile.mkdirs();
}
if (logger.isInfoEnabled()) {
logger.info("开始获取远程文件:[{}]---->[{}]", new Object[] { directory, saveFile });
}
client = getFTPClient(sftpConfig);
client.changeWorkingDirectory(directory);
if (logger.isInfoEnabled()) {
logger.info("打开远程文件:[{}]", new Object[] { directory });
}
output = new FileOutputStream(new File(saveFile.concat(File.separator).concat(downloadFile)));
client.retrieveFile(downloadFile, output);
if (logger.isInfoEnabled()) {
logger.info("文件下载成功");
}
client.logout();
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("文件下载出现异常,[{}]", e);
}
throw new RuntimeException("文件下载出现异常,[{}]", e);
} finally {
close(client, output);
}
}
/**
* 下载远程文件夹下的所有文件
*
* @param remoteFilePath
* @param localDirPath
* @return
* @throws Exception
*/
public static void getFileDir(String remoteFilePath, String localDirPath, FtpOrSftpConfig sftpConfig,
FTPClient client) throws Exception {
File localDirFile = new File(localDirPath);
// 判断本地目录是否存在,不存在需要新建各级目录
if (!localDirFile.exists()) {
localDirFile.mkdirs();
}
if (logger.isInfoEnabled()) {
logger.info("ftp文件服务器文件夹[{}],下载到本地目录[{}]", new Object[] { remoteFilePath, localDirFile });
}
boolean flag = client.changeWorkingDirectory(new String(remoteFilePath.getBytes(),FTP.DEFAULT_CONTROL_ENCODING));
System.out.println(flag);
FTPFile[] lsEntries = client.listFiles(new String(remoteFilePath.getBytes(),FTP.DEFAULT_CONTROL_ENCODING));
for (FTPFile entry : lsEntries) {
String fileName = new String(entry.getName().getBytes(FTP.DEFAULT_CONTROL_ENCODING),"UTF-8");
if (checkFileName(fileName)) {
continue;
}
if (entry.isFile()) {
OutputStream output = new FileOutputStream(new File(localDirPath.concat(File.separator) + fileName));
client.retrieveFile(fileName, output);
output.close();
} else {
File dirFile = new File(localDirPath + File.separator + fileName + File.separator);
// File dirFile = new File(localDirPath +"/" + fileName + "/");
if (!dirFile.exists()) {
dirFile.mkdirs();
}
getFileDir(remoteFilePath + File.separator + fileName+File.separator, localDirPath + File.separator + fileName+File.separator,
sftpConfig, client);
// getFileDir(remoteFilePath + "/" + fileName+"/", localDirPath +"/" + fileName+"/",
// sftpConfig, client);
}
if (logger.isInfoEnabled()) {
logger.info("文件下载成功");
}
}
}
private static boolean checkFileName(String fileName) {
if (".".equals(fileName) || "..".equals(fileName)) {
return true;
}
return false;
}
/**
* Description: 向FTP服务器上传文件
*
* @param hostname FTP服务器hostname
* @param username 账号
* @param password 密码
* @param port 端口
* @param localFilePath 本地文件位置
* @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
* @param fileName ftp文件名称
* @param in 文件流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String localFilePath, FtpOrSftpConfig sftpConfig) {
boolean flag = false;
FTPClient client = null;
InputStream in = null;
try {
client = getFTPClient(sftpConfig);
File file = new File(localFilePath);
in = new FileInputStream(file);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
return flag;
}
// client.setControlEncoding("UTF-8"); // 中文支持
client.setFileType(FTPClient.BINARY_FILE_TYPE);
client.makeDirectory(sftpConfig.getFilePath());
boolean b = client.changeWorkingDirectory(new String(sftpConfig.getFilePath().getBytes(),FTP.DEFAULT_CONTROL_ENCODING));
System.out.println("转换目录结果2:" + b);
// 上传文件
client.enterLocalPassiveMode();
flag = client.storeFile(new String(file.getName().getBytes(),FTP.DEFAULT_CONTROL_ENCODING), in);
System.out.println(flag);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(client, in);
}
return flag;
}
/**
* 关闭资源
*
* @param client
* @param in
*/
private static void close(FTPClient client, InputStream in) {
try {
if (client != null && client.isConnected()) {
client.disconnect();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
System.out.println("系统异常");
}
}
/**
* 关闭资源
*
* @param client
* @param out
*/
private static void close(FTPClient client, OutputStream out) {
try {
if (client != null && client.isConnected()) {
client.disconnect();
}
if (out != null) {
out.close();
}
} catch (Exception e) {
System.out.println("系统异常");
}
}
}
public class FtpOrSftpConfig {
private String hostname;
private Integer port;
private String username;
private String password;
private Integer timeout;
private Resource privateKey;
private String remoteRootPath;
private String fileSuffix;
private String filePath;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public Resource getPrivateKey() {
return privateKey;
}
public void setPrivateKey(Resource privateKey) {
this.privateKey = privateKey;
}
public String getRemoteRootPath() {
return remoteRootPath;
}
public void setRemoteRootPath(String remoteRootPath) {
this.remoteRootPath = remoteRootPath;
}
public String getFileSuffix() {
return fileSuffix;
}
public void setFileSuffix(String fileSuffix) {
this.fileSuffix = fileSuffix;
}
public FtpOrSftpConfig(String hostname, Integer port, String username, String password, Integer timeout,
Resource privateKey, String remoteRootPath, String fileSuffix) {
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
this.timeout = timeout;
this.privateKey = privateKey;
this.remoteRootPath = remoteRootPath;
this.fileSuffix = fileSuffix;
}
public FtpOrSftpConfig(String hostname, Integer port, String username, String password, Integer timeout,
String remoteRootPath) {
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
this.timeout = timeout;
this.remoteRootPath = remoteRootPath;
}
public FtpOrSftpConfig(String hostname, Integer port, String username, String password, Integer timeout,
String filePath,String remoteRootPath) {
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
this.timeout = timeout;
this.filePath = filePath;
this.remoteRootPath = remoteRootPath;
}
public FtpOrSftpConfig() {
}
cs本文由博客群发一文多发等运营工具平台 OpenWrite 发布