maven依赖
commons-net
commons-net
3.3
工具类代码
package com.example.cc.util;
import java.io.*;
import java.net.SocketException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
/**
* FtpUtil 工具类(有Client版)
* @see
* @since
*/
public class FtpOperateUtil {
/**
* LOG
*/
private static final Logger logger = LoggerFactory.getLogger(FtpOperateUtil.class);
/**
* 路径的分隔符
*/
public static final String FILE_SEPARATOR_REG = File.separator.equals("/") ? File.separator : File.separator + File.separator;
/**
* 本地字符编码 ,先初始化为null
*/
private static String LOCAL_CHARSET = "GBK";
/**
* FTP协议里面,规定文件名编码为iso-8859-1
*/
private static String SERVER_CHARSET = "ISO-8859-1";
/**
*
* Description: 获取FTP客户端
* @param url 服务器ip
* @param port 端口号
* @param username 用户名
* @param password 密码
* @return FTPClient
* @throws IOException
* @throws SocketException
* @see
*/
public static FTPClient getFTPClient(String url, int port, String username, String password)
throws SocketException, IOException {
FTPClient ftp = new FTPClient();
int reply;
//连接FTP服务器
ftp.setConnectTimeout(60000);
ftp.connect(url, port);
//登录
ftp.login(username, password);
reply = ftp.getReplyCode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return ftp;
}
if (FTPReply.isPositiveCompletion(ftp.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
LOCAL_CHARSET = "UTF-8";
} else {
LOCAL_CHARSET = System.getProperty("file.encoding");
}
logger.info("系统默认编码:" + LOCAL_CHARSET);
ftp.setControlEncoding(LOCAL_CHARSET);
return ftp;
}
/**
* Description: 向FTP服务器上传文件
* @param ftp ftp客户端
* @param path FTP服务器保存目录
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(FTPClient ftp, String path, String filename, InputStream input) {
boolean success = false;
try {
//切换到FTP服务器保存目录
String pwd = ftp.printWorkingDirectory();
ftp.changeWorkingDirectory(pwd);
logger.info("当前工作目录为" + pwd);
boolean changeWorkingDirectory = ftp.changeWorkingDirectory(path);
if (!changeWorkingDirectory) {
path = path.replaceAll("/", FILE_SEPARATOR_REG).replaceAll("\\\\", FILE_SEPARATOR_REG);
String[] split = null;
split = path.split(FILE_SEPARATOR_REG);
for (int i = 0; i < split.length; i++ ) {
if (!ftp.changeWorkingDirectory(split[i])) {
ftp.makeDirectory(split[i]);
ftp.changeWorkingDirectory(split[i]);
}
}
} else {
ftp.changeWorkingDirectory(path);
}
//设置当前的数据连接模式
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
ftp.setBufferSize(512 * 1024);
ftp.enterLocalPassiveMode();
//存储文件使用给定的文件名,并输入从给定的InputStream。
success = ftp.storeFile(new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET), input);
logger.info("文件上传后的reply = " + ftp.getReplyCode());
logger.info("文件上传后的replyString = " + ftp.getReplyString());
input.close();
ftp.logout();
} catch (IOException e) {
e.getMessage();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
e.getMessage();
}
}
}
return success;
}
/**
* Description: 从FTP服务器下载文件
* @param ftp ftp客户端
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return boolean
*/
public static boolean downFile(FTPClient ftp, String remotePath, String fileName, String localPath) {
boolean success = false;
try {
//切换到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftp.enterLocalPassiveMode();
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
success = true;
} catch (IOException e) {
e.getMessage();
}
return success;
}
/**
*
* Description:目录下是否有同名的文件
* @param ftp Ftp客户端
* @param remotePath 远程目录
* @param fileName 文件名
* @return boolean
* @see
*/
public static boolean hasSameName(FTPClient ftp, String remotePath, String fileName) {
logger.info("进入 --hasSameName()方法中");
//切换到FTP服务器目录
try {
ftp.changeWorkingDirectory(ftp.printWorkingDirectory());
boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath);
if (!changeWorkingDirectory) {
logger.info("changeWorkingDirectory = " + changeWorkingDirectory);
remotePath = remotePath.replaceAll("/", FILE_SEPARATOR_REG).replaceAll("\\\\", FILE_SEPARATOR_REG);
logger.info("remotePath = " + remotePath);
String[] split = null;
split = remotePath.split(FILE_SEPARATOR_REG);
for (int i = 0; i < split.length; i++ ) {
logger.info("printWorkingDirectory() = " + ftp.printWorkingDirectory());
if (!ftp.changeWorkingDirectory(split[i])) {
ftp.makeDirectory(split[i]);
ftp.changeWorkingDirectory(split[i]);
} else {
ftp.changeWorkingDirectory(split[i]);
}
}
ftp.enterLocalPassiveMode();
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
logger.info("文件名:-- " + ff.getName());
if (ff.getName().equals(fileName)) {
return true;
}
}
} else {
ftp.enterLocalPassiveMode();
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
logger.info("文件名:-- " + ff.getName());
if (ff.getName().equals(fileName)) {
return true;
}
}
}
} catch (IOException e) {
e.getMessage();
}
return false;
}
/**
* 删除FTP上的文件
* @param ftp
* @param remotePath
* @param fileName
* @return
*/
public static Map deleteFile(FTPClient ftp, String remotePath, String fileName) {
Map map = new HashMap<>();
boolean has = hasSameName(ftp, remotePath, fileName);
if (has == true) {
try {
if (ftp.deleteFile(fileName)) {
map.put("state", 200);
} else {
map.put("error", "或权限不足没有将FTP文件删除");
logger.info("文件"+fileName+"删除失败,权限不足没有将FTP文件删除");
}
} catch (IOException e) {
map.put("error", "删除FTP文件的过程中出现错误");
e.getMessage();
}
} else {
map.put("error", "要删除的文件不存在");
}
return map;
}
/**
* @param fileName
* @return function:从服务器上读取指定的文件
* @throws ParseException
* @throws IOException
*/
public static String readFile(FTPClient ftp, String fileName)
throws ParseException {
InputStream ins = null;
StringBuilder builder = null;
try {
// 从服务器上读取指定的文件
ftp.enterLocalPassiveMode();
ins = ftp.retrieveFileStream(new String(fileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET));
BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
String line;
builder = new StringBuilder(150);
while ((line = reader.readLine()) != null) {
logger.info(line);
builder.append(line);
}
reader.close();
if (ins != null) {
ins.close();
}
// 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
ftp.getReply();
} catch (IOException e) {
e.getMessage();
}
return builder.toString();
}
/**
* 获取ftp下的工作目录的路径
* @param ftp
* @param path
* @return
*/
public static List getDirList(FTPClient ftp, String path) {
List fileLists = new ArrayList<>();
// 获得指定目录下所有文件名
FTPFile[] ftpFiles = null;
try {
ftp.enterLocalPassiveMode();
ftpFiles = ftp.listFiles(path);
} catch (IOException e) {
e.getMessage();
}
for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++ ) {
FTPFile file = ftpFiles[i];
if (file.isDirectory()) {
fileLists.add(file.getName() + "/");
}
}
return fileLists;
}
/**
* 获取ftp下的工作目录的路径
* @param ftp
* @param path
* @return
*/
public static List getFileList(FTPClient ftp, String path) {
List fileLists = new ArrayList<>();
// 获得指定目录下所有文件名
FTPFile[] ftpFiles = null;
try {
ftp.enterLocalPassiveMode();
ftpFiles = ftp.listFiles(path);
} catch (IOException e) {
e.getMessage();
}
for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++ ) {
FTPFile file = ftpFiles[i];
if (!file.isDirectory()) {
fileLists.add(file.getName());
}
}
return fileLists;
}
// public static void main(String[] arg)
// throws FileNotFoundException {
// String url = "192.168.3.9";
// int port = 21;
// String username = "peter";
// String password = "08A189769D1B82AA";
// File file = new File("C:\\Users\\peter\\Desktop\\4501.xls");
// FileInputStream inputStream = new FileInputStream(file);
// DESUtil.encrypt("");
// try {
// FTPClient ftpClient = FtpOperateUtil.getFTPClient(url, port, username, DESUtil.decrypt(password));
// FtpOperateUtil.uploadFile(ftpClient, "/ss", "PNR_20200325144501.xls", inputStream);
// // FTPClient ftpClient2 = FtpUtil2.getFTPClient(url, port, username, password);
// // ftpClient2.changeWorkingDirectory("metafiletest/test");
// // ftpClient2.setFileType(FTPClient.BINARY_FILE_TYPE);
// // String str =FtpUtil2.readFile(ftpClient2,"我的string.txt");
// //ftpClient.changeWorkingDirectory("metafiletest/test");
// //ftpClient.changeWorkingDirectory("/metafiletest/test");
// } catch (IOException e) {
// e.getMessage();
// }
// }
}