package com.receive.tools; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; 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.apache.log4j.Logger; /** * FTP tools */ public class FtpUtils { private static final Logger logger = Logger.getLogger(FtpUtils.class); // ftp server address private static final String hostName = PropertiesReader.getProperty("ftp.hostName"); // The default ftp server port number is 21 private static final Integer port = PropertiesReader.getIntProperty("ftp.port", 21); // ftp login account private static final String userName = PropertiesReader.getProperty("ftp.userName"); // ftp login password private static final String passWord = PropertiesReader.getProperty("ftp.passWord"); // operation file path private static final String path = PropertiesReader.getProperty("ftp.path"); // ftp client instance object private static FTPClient ftpClient; static { ftpClient = new FTPClient(); ftpClient.setControlEncoding("utf-8"); } /** * Log in to the ftp server * * @return whether the login is successful */ private static final boolean loginFTP() { try { ftpClient.connect(hostName, port); // connect to ftp server ftpClient.login(userName, passWord); // login to ftp server int replyCode = ftpClient.getReplyCode(); // Whether the server is successfully logged in if (!FTPReply.isPositiveCompletion(replyCode)) { logger.error("Failed to connect to ftp server:" + hostName + ":" + port); System.out.println("Failed to connect to ftp server:" + hostName + ":" + port); ftpClient.disconnect(); return false; } logger.info("Successful connection to ftp server:" + hostName + ":" + port); System.out.println("Successful connection to ftp server:" + hostName + ":" + port); ftpClient.makeDirectory(path); ftpClient.changeWorkingDirectory(path); } catch (Exception e) { logger.error("Exception information is", e); System.out.println("Exception information is " + e); } return true; } /** * upload files * * @param fileName * File name uploaded to ftp * @param originFileName * The original absolute path of the uploaded file * @return */ private static final boolean uploadFile(String fileName, String originFileName) { boolean result = false; InputStream inputStream = null; try { inputStream = new FileInputStream(new File(originFileName)); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); result = ftpClient.storeFile(fileName, inputStream); inputStream.close(); if (result) { logger.info("Uploaded file successfully" + fileName); System.out.println("Uploaded file successfully" + fileName); } } catch (Exception e) { logger.error("Failed to upload file" + fileName); System.out.println("Failed to upload file" + fileName); logger.error("Exception message is" + e.getMessage()); System.out.println("Exception message is" + e.getMessage()); close(); } finally { if (null != inputStream) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace (); } } } return result; } /** * Determine whether the ftp server file exists * * @param path * @return * @throws IOException */ private static final boolean existFile(String fileName) { boolean flag = false; FTPFile[] ftpFileArr; try { ftpFileArr = ftpClient.listFiles(fileName); if (ftpFileArr.length > 0) { flag = true; logger.info("Find the file successfully and exists" + fileName); System.out.println("Find the file successfully and exists" + fileName); } else { logger.info("Find file does not exist" + fileName); System.out.println("Search file does not exist" + fileName); } } catch (IOException e) { logger.error("Failed to find file" + fileName); System.out.println("Failed to find file" + fileName); logger.error("Exception information is", e); System.out.println("Exception information is " + e); close(); } return flag; } /** * * download file * * * @param filename * file name * * @param localpath * Downloaded file path * * @return */ @SuppressWarnings("unused") private static final boolean downloadFile(String fileName, String localpath) { boolean flag = false; OutputStream os = null; try { FTPFile[] ftpFiles = ftpClient.listFiles(); for (FTPFile file : ftpFiles) { if (fileName.equalsIgnoreCase(file.getName())) { File localFile = new File(localpath + File.separator + file.getName()); os = new FileOutputStream(localFile); ftpClient.retrieveFile(file.getName(), os); os.close(); } } flag = true; logger.info("Successfully downloaded file" + fileName); System.out.println("Successfully downloaded file" + fileName); } catch (Exception e) { logger.error("Failed to download file" + fileName); System.out.println("Failed to download file" + fileName); logger.error("Exception information is", e); System.out.println("Exception information is " + e); close(); } finally { if (null != os) { try { os.close(); } catch (IOException e) { logger.error("Exception information is", e); System.out.println("Exception information is " + e); } } } return flag; } /** * * Delete Files * * * @param pathname * FTP server save directory * * @param filename *name of file to delete* * @return */ private static final boolean deleteFile(String fileName) { boolean flag = false; try { if (FTPReply.FILE_ACTION_OK == ftpClient.dele(fileName)) { flag = true; logger.info("Delete file successfully" + fileName); System.out.println("Delete file successfully" + fileName); } else { logger.info("Failed to delete file" + fileName); System.out.println("Failed to delete file" + fileName); } } catch (Exception e) { logger.error("Failed to delete file" + fileName); System.out.println("Failed to delete file" + fileName); logger.error("Exception message is" + e.getMessage()); System.out.println("Exception message is" + e.getMessage()); } return flag; } /** * rename file * * @param srcFname * Original subject * @param targetFname * new filename * @return */ private static final boolean renameFile(String srcFname, String targetFname) { boolean flag = false; if (ftpClient != null) { try { flag = ftpClient.rename(srcFname, targetFname); if (flag) { logger.info("Renamed the file successfully, the original file name is " + srcFname + ", the renamed file name is " + targetFname); System.out.println("Renamed the file successfully, the original file name is " + srcFname + ", the renamed file name is " + targetFname); } } catch (IOException e) { logger.error("Failed to rename the file, the original file name is " + srcFname); System.out.println("Failed to rename the file, the original file name is " + srcFname); logger.error("Exception information is", e); System.out.println("Exception information is " + e); close(); } } return flag; } /** * Close the ftp client and release resources */ private static final void close() { if (null != ftpClient) { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { logger.error("Exception information is", e); System.out.println("Exception information is " + e); } } } } /** * ftp upload file * * @param filePath * file full path * @return */ public static boolean ftpUploadFile(String filePath) { if (loginFTP()) {// Login to the ftp server String fileName = filePath; fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length()); String newFileName = fileName + ".tmp"; if (uploadFile(newFileName, filePath)) {// upload file if (existFile(newFileName)) {// Determine whether the specified file exists if (deleteFile(newFileName)) {// delete the existing file if (renameFile(newFileName, fileName)) {// Rename the file after successful deletion if (DirFileUtils.deleteFile(filePath)) {// delete this file on this machine return true; } } } } else { if (renameFile(newFileName, fileName)) {// rename the file if (DirFileUtils.deleteFile(filePath)) {// delete this file on this machine return true; } } } } } close(); // close the client return false; } }
Need to introduce maven dependencies
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency>