public classFTPUtils {private static final Logger LOG = LoggerFactory.getLogger(FTPUtils.class);/*** 获取FTPClient对象
*
*@paramftpHost FTP主机服务器
*@paramftpPassword FTP 登录密码
*@paramftpUserName FTP登录用户名
*@paramftpPort FTP端口 默认为21
*@return
*/
private staticFTPClient getFTPClient(String ftpHost, String ftpPassword,
String ftpUserName,int ftpPort) throwsIOException {
FTPClient ftpClient= null;
ftpClient= newFTPClient();
ftpClient.connect(ftpHost, ftpPort);//连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);//登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
LOG.info("未连接到FTP,用户名或密码错误。");
ftpClient.disconnect();
}else{
LOG.info("FTP连接成功。");
}returnftpClient;
}/*** 去 服务器的FTP路径下上读取文件
*
*@paramftpPath
*@param*@return
*/
public static ListreadConfigFileForFTP(String ftpPath, String ftpHost, String ftpPassword,
String ftpUserName,intftpPort) {
InputStream in;
FTPClient ftpClient= null;try{
ftpClient=getFTPClient(ftpHost, ftpPassword, ftpUserName, ftpPort);
List list = new ArrayList<>();
LOG.info("开始读取绝对路径" + ftpPath + "文件!");try{
ftpClient.setControlEncoding("UTF-8"); //中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);
FTPFile[] ftpFiles=ftpClient.listFiles(ftpPath);for(FTPFile file : ftpFiles) {
String name=file.getName();
in= ftpClient.retrieveFileStream(new String(name.getBytes("UTF-8"), "ISO-8859-1"));if (in != null) {
StringBuffer resultBuffer= newStringBuffer();
BufferedReader br= new BufferedReader(newInputStreamReader(in));
String data;try{while ((data = br.readLine()) != null) {
resultBuffer.append(data);
}
String string=resultBuffer.toString();
JSONArray jsonArray=JSONArray.parseArray(string);
list.add(jsonArray);
in.close();boolean flag =ftpClient.deleteFile(name);if(flag) {
System.out.println("删除文件成功");
}
pletePendingCommand();
}catch(IOException e) {
LOG.error("文件读取错误。");
e.printStackTrace();
}
}else{
LOG.error("in为空,不能读取。");
}
}
}catch(FileNotFoundException e) {
LOG.error("没有找到" + ftpPath + "文件");
e.printStackTrace();
}catch(SocketException e) {
LOG.error("连接FTP失败.");
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
LOG.error("文件读取错误。");
}returnlist;
}catch(SocketException e) {
LOG.info("FTP的IP地址可能错误,请正确配置。");
}catch(IOException e) {
LOG.info("FTP的端口错误,请正确配置。");
}return null;
}/*** * 删除文件 *
*
*@parampathname FTP服务器保存目录 *
*@paramfilename 要删除的文件名称 *
*@return
*/
private static voiddeleteFile(String pathname, String filename, FTPClient ftpClient) {try{
System.out.println("开始删除文件");//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);boolean flag =ftpClient.deleteFile(filename);
ftpClient.logout();if(flag) {
System.out.println("删除文件成功");
}
}catch(Exception e) {
System.out.println("删除文件失败");
e.printStackTrace();
}finally{if(ftpClient.isConnected()) {try{
ftpClient.disconnect();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
}