FTP is the English abbreviation of File Transfer Protocol (File Transfer Protocol), and the Chinese abbreviation is called "Written Transfer Protocol". Used for bidirectional transfer of control files on the Internet. At the same time, it is also an application. There are different FTP applications based on different operating systems, and all of these applications adhere to the same protocol to transfer files. In the use of FTP, users often encounter two concepts: "Download" and "Upload". "Download" files means copying files from the remote host to your own computer; "uploading" files means copying files from your own computer to the remote host. In the Internet language, users can upload (download) files to (from) remote hosts through client programs.
First, Serv-U was downloaded to set up your computer as an FTP file server for easy operation. The following code is used in the FTP server and the relevant data of the FTP connection must be written in the code to complete it.
1. Upload and download of FTP files (note that it is upload and download of individual files)
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 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;/** * Implement FTP file upload and file download*/public class FtpApche { private static FTPClient ftpClient = new FTPClient(); private static String encoding = System.getProperty("file.encoding"); /** * Description: Upload files to the FTP server* * @Version1.0 * @param url * FTP server hostname * @param port * FTP server port* @param username * FTP login account* @param password * FTP login password* @param path * FTP server saves directory, if it is the root directory, it is "/" * @param filename * File name uploaded to the FTP server* @param input * Local file input stream* @return Return true successfully, otherwise it will return false */ public static boolean uploadFile(String url, int port, String username, String password, String path, String filename, InputStream input) { boolean result = false; try { int reply; // If you use the default port, you can directly connect to the FTP server ftpClient.connect(url); // ftp.connect(url, port);// Connect the FTP server// Log in to ftpClient.login(username, password); ftpClient.setControlEncoding(encoding); // Verify that the connection is successful reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { System.out.println("Connection failed"); ftpClient.disconnect(); return result; } // Transfer the working directory to the specified directory boolean change = ftpClient.changeWorkingDirectory(path); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (change) { result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input); if (result) { System.out.println("Uploaded successfully!"); } } input.close(); ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { } } } return result; } /** * Upload local files to the FTP server* */ public void testUpLoadFromDisk() { try { FileInputStream in = new FileInputStream(new File("D:/test02/list.txt")); boolean flag = uploadFile("10.0.0.102", 21, "admin","123456", "/", "lis.txt", in); System.out.println(flag); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Description: Download the file from the FTP server* * @Version1.0 * @param url * FTP server hostname * @param port * FTP server port* @param username * FTP login account* @param password * FTP login password* @param remotePath * Relative path on the FTP server* @param fileName * File name to download * @param localPath * Path to save to local after downloading * @return */ public static boolean downFile(String url, int port, String username, String password, String remotePath, String fileName, String localPath) { boolean result = false; try { int reply; ftpClient.setControlEncoding(encoding); /* * In order to upload and download Chinese files, some places recommend using the following two sentences instead of * new String(remotePath.getBytes(encoding),"iso-8859-1") transcoding. * After testing, it cannot be passed. */// FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);// conf.setServerLanguageCode("zh"); ftpClient.connect(url, port); // If the default port is used, you can directly connect to the FTP server by ftpClient.login(username, password);// Login// Set the file transfer type to binary ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // Get the ftp login response code reply = ftpClient.getReplyCode(); // Verify that the login is successful if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return result; } // Transfer to the FTP server directory to the specified directory ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1")); // Get the file list FTPFile[] fs = ftpClient.listFiles(); for (FTPFile ff : fs) { if (ff.getName().equals(fileName)) { File localFile = new File(localPath + "/" + ff.getName()); OutputStream is = new FileOutputStream(localFile); ftpClient.retrieveFile(ff.getName(), is); is.close(); } } ftpClient.logout(); result = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { } } } return result; } /** * Download the file on the FTP server to the local * */ public void testDownFile() { try { boolean flag = downFile("10.0.0.102", 21, "admin", "123456", "/", "ip.txt", "E:/"); System.out.println(flag); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { FtpApche fa = new FtpApche(); fa.testDownFile(); fa.testUpLoadFromDisk(); }}2. Upload and download of FTP folders (note that the entire folder is the entire folder)
package ftp;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.TimeZone;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPClientConfig;import org.apache.commons.net.ftp.FTPFile;import org.apache.commons.net.ftp.FTPReply;import org.apache.log4j.Logger;public class FTPTest_04 { private FTPClient ftpClient; private String strIp; private int intPort; private String user; private String password; private static Logger logger = Logger.getLogger(FTPTest_04.class.getName()); /* * * Ftp constructor*/ public FTPTest_04(String strIp, int intPort, String user, String Password) { this.strIp = strIp; this.intPort = intPort; this.user = user; this.password = Password; this.ftpClient = new FTPClient(); } /** * @return Determine whether the login is successful* */ public boolean ftpLogin() { boolean isLogin = false; FTPClientConfig ftpClientConfig = new FTPClientConfig(); ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); this.ftpClient.setControlEncoding("GBK"); this.ftpClient.configure(ftpClientConfig); try { if (this.intPort > 0) { this.ftpClient.connect(this.strIp, this.intPort); }else { this.ftpClient.connect(this.strIp); } // FTP server connection answer int reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); logger.error("Login to the FTP service failed! "); return isLogin; } this.ftpClient.login(this.user, this.password); // Set the transmission protocol this.ftpClient.enterLocalPassiveMode(); this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); logger.info("Congratulations" + this.user + "Successfully logged into the FTP server"); isLogin = true; }catch (Exception e) { e.printStackTrace(); logger.error(this.user + "Login to the FTP service failed!" + e.getMessage()); } this.ftpClient.setBufferSize(1024 * 2); this.ftpClient.setDataTimeout(30 * 1000); return isLogin; } /** * @Exit Close Server Link* */ public void ftpLogOut() { if (null != this.ftpClient && this.ftpClient.isConnected()) { try { boolean reuslt = this.ftpClient.logout();// Exit FTP server if (reuslt) { logger.info("Successfully exited the server"); } } catch (IOException e) { e.printStackTrace(); logger.warn("Exception of exiting the FTP server!" + e.getMessage()); } finally { try { this.ftpClient.disconnect();// Close the connection to the FTP server}catch (IOException e) { e.printStackTrace(); logger.warn("Exception of closing the FTP server's connection!"); } } } } } /*** * Upload the Ftp file* @param localFile Local file* @param romotUpLoadePath Upload server path- should end with/* */ public boolean uploadFile(File localFile, String romotUpLoadePath) { BufferedInputStream inStream = null; boolean success = false; try { this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// Change the working path inStream = new BufferedInputStream(new FileInputStream(localFile)); logger.info(localFile.getName() + "Start upload..."); success = this.ftpClient.storeFile(localFile.getName(), inStream); if (success == true) { logger.info(localFile.getName() + "uploaded successfully"); return success; } } catch (FileNotFoundException e) { e.printStackTrace(); logger.error(localFile + "Not Found"); }catch (IOException e) { e.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); }catch (IOException e) { e.printStackTrace(); } } } return success; } /*** * Download file* @param remoteFileName File name to be downloaded* @param localDires Download to the local path* @param remoteDownLoadPath The path where remoteFileName is located* */ public boolean downloadFile(String remoteFileName, String localDires, String remoteDownLoadPath) { String strFilePath = localDires + remoteFileName; BufferedOutputStream outStream = null; boolean success = false; try { this.ftpClient.changeWorkingDirectory(remoteDownLoadPath); outStream = new BufferedOutputStream(new FileOutputStream( strFilePath)); logger.info(remoteFileName + "Start download..."); success = this.ftpClient.retrieveFile(remoteFileName, outStream); if (success == true) { logger.info(remoteFileName + "Successfully downloaded to" + strFilePath); return success; } }catch (Exception e) { e.printStackTrace(); logger.error(remoteFileName + "Download failed"); } finally { if (null != outStream) { try { outStream.flush(); outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } if (success == false) { logger.error(remoteFileName + "Download failed!!!"); } return success; } /*** * @upload folder* @param localDirectory * Local folder* @param remoteDirectoryPath * Ftp Server path ends with directory "/"* */ public boolean uploadDirectory(String localDirectory, String remoteDirectoryPath) { File src = new File(localDirectory); try { remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/"; boolean makeDirFlag = this.ftpClient.makeDirectory(remoteDirectoryPath); System.out.println("localDirectory: " + localDirectory); System.out.println("remoteDirectoryPath: " + remoteDirectoryPath); System.out.println("src.getName(): " + src.getName()); System.out.println("remoteDirectoryPath: " + remoteDirectoryPath); System.out.println("makeDirFlag : " + makeDirFlag); // ftpClient.listDirectories(); }catch (IOException e) { e.printStackTrace(); logger.info(remoteDirectoryPath + "Directory creation failed"); } File[] allFile = src.listFiles(); for (int currentFile = 0;currentFile < allFile.length;currentFile++) { if (!allFile[currentFile].isDirectory()) { String srcName = allFile[currentFile].getPath().toString(); uploadFile(new File(srcName), remoteDirectoryPath); } } for (int currentFile = 0;currentFile < allFile.length;currentFile++) { if (allFile[currentFile].isDirectory()) { // Recursive uploadDirectory(allFile[currentFile].getPath().toString(), remoteDirectoryPath); } } return true; } /*** * @Download folder* @param localDirectoryPath local address* @param remoteDirectory remote folder* */ public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) { try { String fileName = new File(remoteDirectory).getName(); localDirectoryPath = localDirectoryPath + fileName + "//"; new File(localDirectoryPath).mkdirs(); FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory); for (int currentFile = 0;currentFile < allFile.length;currentFile++) { if (!allFile[currentFile].isDirectory()) { downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory); } } for (int currentFile = 0;currentFile < allFile.length;currentFile++) { if (allFile[currentFile].isDirectory()) { String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName(); downLoadDirectory(localDirectoryPath,strremoteDirectoryPath); } } } catch (IOException e) { e.printStackTrace(); logger.info("Download folder failed"); return false; } return true; } // FtpClient Set and Get functions public FTPClient getFtpClient() { return ftpClient; } public void setFtpClient(FTPClient ftpClient) { this.ftpClient = ftpClient; } public static void main(String[] args) throws IOException { FTPTest_04 ftp=new FTPTest_04("10.0.0.102",21,"admin","123456"); ftp.ftpLogin(); System.out.println("1"); //Upload folder boolean uploadFlag = ftp.uploadDirectory("D://test02", "/"); //If it is admin/, then all files are passed. If it is just/, then it is passed on the folder System.out.println("uploadFlag : " + uploadFlag); //Download folder ftp.downLoadDirectory("d://tm", "/"); ftp.ftpLogOut(); }}The above is all the content of this article. I hope that the content of this article will be of some help to everyone’s study or work. I also hope to support Wulin.com more!