Apache FTP is a widely used FTP upload client tool. It is easy to operate, has simple code and clear structure. It is a priority for FTP file client management software. FTP operations include: FTP file upload (breakpoint continuous transmission), FTP file download, FTP file renaming, and FTP file deletion. These operations have fully demonstrated the FTP application management method. So I have always used this method to implement the management of FTP file servers; attached with FTP tool code.
1. FTP file operation status enumeration class
package com.scengine.wtms.utils.ftp; public enum FTPStatus { File_Exits(0), Create_Directory_Success(1), Create_Directory_Fail(2), Upload_From_Break_Success(3), Upload_From_Break_Faild(4), Download_From_Break_Success(5), Download_From_Break_Faild(6), Upload_New_File_Success(7), Upload_New_File_Failed(8), Delete_Remote_Success(9), Delete_Remote_Faild(10),Remote_Bigger_Local(11),Remote_smaller_local(12),Not_Exist_File(13),Remote_Rename_Success(14),Remote_Rename_Faild(15),File_Not_Unique(16); private int status; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } FTPStatus(int status) { this.status = status; } } 2. FTP file operation tool code
package com.scengine.wtms.utils.ftp; 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 java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.commons.net.PrintCommandListener; 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.scengine.wtms.utils.Log; public class FTPUtils { private FTPClient ftpClient = new FTPClient(); /** * Object construction settings output the commands used in the process to the console*/ public FTPUtils() { this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); } /** * * Used to connect to the FTP server in java programming* * @param hostname * Hostname * * @param port * Port * * @param username * Username * * @param password * Password * @return Whether the connection is successful* * @throws IOException */ public boolean connect(String hostname, int port, String username, String password) throws IOException { ftpClient.connect(hostname, port); if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { if (ftpClient.login(username, password)) { return true; } } disconnect(); return false; } /** * Delete remote FTP file* * @param remote * Remote file path* @return * @throws IOException */ public FTPStatus delete(String remote) throws IOException { ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); FTPStatus result = null; FTPFile[] files = ftpClient.listFiles(remote); if (files.length == 1) { boolean status = ftpClient.deleteFile(remote); result = status ? FTPStatus.Delete_Remote_Success : FTPStatus.Delete_Remote_Faild; } else { result = FTPStatus.Not_Exist_File; } Log.getLogger(this.getClass()).info("FTP server file deletion identifier: "+result); return result; } /** * Rename the remote FTP file* * @param name * New remote file name (path-must be guaranteed to be under the same path) * * @param remote * Remote file path* * @return Whether it is successful* * @throws IOException */ public FTPStatus rename(String name,String remote) throws IOException { ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); FTPStatus result = null; FTPFile[] files = ftpClient.listFiles(remote); if (files.length == 1) { boolean status = ftpClient.rename(remote, name); result = status ? FTPStatus.Remote_Rename_Success : FTPStatus.Remote_Rename_Faild; } else { result = FTPStatus.Not_Exist_File; } Log.getLogger(this.getClass()).info("FTP server filename update identifier: "+result); return result; } /** * * Download file from the FTP server* * @param fileName * Download file name (including suffix name) * * @param remote * Remote file path* * @param local * Local file path* * @return Whether it is successful* * @throws IOException */ public FTPStatus download(String fileName,String remote,HttpServletResponse response) throws IOException { // Open the output stream pop-up file save path selection window response.setContentType("application/octet-stream"); response.setContentType("application/OCTET-STREAM;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" +fileName); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); FTPStatus result; OutputStream out = response.getOutputStream(); boolean status = ftpClient.retrieveFile(remote, out); result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild; Log.getLogger(this.getClass()).info("FTP server file download identifier: "+result); out.close(); return result; } /** * Download file from FTP server* * @param remote * Remote file path* * @param local * Local file path * * @return Whether it is successful* * @throws IOException */ @SuppressWarnings("resource") public FTPStatus download(String remote, String local) throws IOException { ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); FTPStatus result; File f = new File(local); FTPFile[] files = ftpClient.listFiles(remote); if (files.length != 1) { Log.getLogger(this.getClass()).info("Remote file is not unique"); return FTPStatus.File_Not_Unique; } long lRemoteSize = files[0].getSize(); if (f.exists()) { OutputStream out = new FileOutputStream(f, true); Log.getLogger(this.getClass()).info("Local file size is:" + f.length()); if (f.length() >= lRemoteSize) { Log.getLogger(this.getClass()).info("The local file size is greater than the remote file size, download aborted"); return FTPStatus.Remote_smaller_local; } ftpClient.setRestartOffset(f.length()); boolean status = ftpClient.retrieveFile(remote, out); result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild; out.close(); } else { OutputStream out = new FileOutputStream(f); boolean status = ftpClient.retrieveFile(remote, out); result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild; out.close(); } return result; } /** * Upload file to the FTP server, support breakpoint continuous transmission* * @param local * Local file name, absolute path* * @param remote * Remote file path, use /home/directory1/subdirectory/file.ext * According to the path specified on Linux, multi-level directory nesting is supported, and recursively creates non-existent directory structures* * @return Upload result* * @throws IOException */ @SuppressWarnings("resource") public FTPStatus upload(String local, String remote) throws IOException { // Set PassiveMode to transmit ftpClient.enterLocalPassiveMode(); // Set to transmit ftpClient.setFileType(FTP.BINARY_FILE_TYPE); FTPStatus result; // Processing of remote directories String remoteFileName = remote; if (remote.contains("/")) { remoteFileName = remote.substring(remote.lastIndexOf("/") + 1); String directory = remote.substring(0, remote.lastIndexOf("/") + 1); if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(directory)) { // If the remote directory does not exist, recursively create the remote server directory int start = 0; int end = 0; if (directory.startsWith("/"))) { start = 1; } else { start = 0; } end = directory.indexOf("/", start); while (true) { String subDirectory = remote.substring(start, end); if (!ftpClient.changeWorkingDirectory(subDirectory)) { if (ftpClient.makeDirectory(subDirectory)) { ftpClient.changeWorkingDirectory(subDirectory); } else { Log.getLogger(this.getClass()).info("Create directory failed"); return FTPStatus.Create_Directory_Fail; } } start = end + 1; end = directory.indexOf("/", start); // Check whether all directories have been created if (end <= start) { break; } } } } } // Check whether there is a file remote FTPFile[] files = ftpClient.listFiles(remoteFileName); if (files.length == 1) { long remoteSize = files[0].getSize(); File f = new File(local); long localSize = f.length(); if (remoteSize == localSize) { return FTPStatus.File_Exits; } else if (remoteSize > localSize) { return FTPStatus.Remote_Bigger_Local; } // Try to move the pointer in the file to realize the interruption of breakpoint InputStream is = new FileInputStream(f); if (is.skip(remoteSize) == remoteSize) { ftpClient.setRestartOffset(remoteSize); if (ftpClient.storeFile(remote, is)) { return FTPStatus.Upload_From_Break_Success; } } // If the breakpoint continues to pass unsuccessfully, delete the file on the server and upload it again if (!ftpClient.deleteFile(remoteFileName)) { return FTPStatus.Delete_Remote_Faild; } is = new FileInputStream(f); if (ftpClient.storeFile(remote, is)) { result = FTPStatus.Upload_New_File_Success; } else { result = FTPStatus.Upload_New_File_Failed; } is.close(); } else { InputStream is = new FileInputStream(local); if (ftpClient.storeFile(remoteFileName, is)) { result = FTPStatus.Upload_New_File_Success; } else { result = FTPStatus.Upload_New_File_Failed; } is.close(); } return result; } /** * * Disconnect from the remote server* * @throws IOException */ public void disconnect() throws IOException { if (ftpClient.isConnected()) { ftpClient.disconnect(); } } public static void main(String[] args) { FTPUtils myFtp = new FTPUtils(); try { myFtp.connect("192.168.1.200", 21, "duser", "HTPDuserXP32"); Log.getLogger(FTPUtils.class).info(myFtp.upload("C://Users//Administrator//Desktop//swing.drawer.jar", "/jars/swing.drawer.jar")); myFtp.disconnect(); } catch (IOException e) { Log.getLogger(FTPUtils.class).info("FTP upload file exception: " + e.getMessage()); } } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.