Preface
Recently, I need to interact with the ftp server in my project. I found a tool class about ftp upload and download on the Internet. There are roughly two types.
The first is a singleton pattern class.
The second type is to define another service, which directly implements the upload and download of ftp through the service.
Both of these feelings have pros and cons.
The first one implements code reuse, but the configuration information needs to be written in the class, which is more complicated to maintain.
The second type is a spring framework, configuration information can be dynamically injected through the properties file, but the code cannot be reused.
So I plan to implement a tool class myself to integrate the above two advantages. By the way, some common problems during the upload process have also been solved.
Because I am using the spring framework, if the tool class is declared as bean for spring management, it is a singleton by default, so I don't need to implement the singleton again. And because it is a bean, I can inject the properties of the properties file into the properties of the bean to decouple. The following is the specific code:
package com.cky.util;import java.io.File;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.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;//using spring automatically generates singleton object, //@Componentpublic class FtpUtil { //automatic injection of @Value("${ftp.host}") private String host; //ftp server ip @Value("${ftp.port}") private int port; //ftp server port @Value("${ftp.username}") private String username;//username@Value("${ftp.password}") private String password;//Password @Value("${ftp.basePath}") private String basePath;//Storage the file's basic path//When testing, open this constructor, set your initial value, and run the test in the main method behind the code/*public FtpUtil() { //System.out.println(this.toString()); host="192.168.100.77"; port=21; username="ftpuser"; password="ftp54321"; basePath="/home/ftpuser/"; }*/ /** * * @param path The path to upload the file to the server* @param filename Upload file name* @param input Input stream* @return */ public boolean fileUpload(String path,String filename,InputStream input) { FTPClient ftp=new FTPClient(); try { ftp.connect(host, port); ftp.login(username, password); //Set the file encoding format ftp.setControlEncoding("UTF-8"); //There are two modes of ftp communication //PORT (active mode) client opens a new port (>1024) and sends commands or transmits data through this port. During this period, the server only uses one port it opens, such as 21 //PASV (passive mode) client sends a PASV command to the server, the server opens a new port (>1024), and uses this port to transmit data with the client's port 21// Due to the uncontrollable client, firewall, etc., the port needs to be opened by the server, and the passive mode ftp.enterLocalPassiveMode(); //Set the transmission mode to stream mode ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); //Get the status code to determine whether the connection is successful if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new RuntimeException("FTP server refuses to connect"); } //Go to the root directory of the uploaded file if(!ftp.changeWorkingDirectory(basePath)) { throw new RuntimeException("The root directory does not exist, needs to be created"); } //Judge whether the directory exists if(!ftp.changeWorkingDirectory(path)) { String[] dirs=path.split("/"); //Create the directory for (String dir : dirs) { if(null==dir||"".equals(dir)) continue; //Judge whether the directory exists if(!ftp.changeWorkingDirectory(dir)) { //Create if(!ftp.makeDirectory(dir)) { throw new RuntimeException("Subdirectory creation failed"); } //Enter the newly created directory ftp.changeWorkingDirectory(dir); } } //Set the uploaded file type to binary type ftp.setFileType(FTP.BINARY_FILE_TYPE); //Upload the file if(!ftp.storeFile(filename, input)) { return false; } input.close(); ftp.logout(); return true; } } catch (Exception e) { throw new RuntimeException(e); } finally { if(ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { throw new RuntimeException(e); } } } return false; } /** * * @param filename filename, note! The file name here is the file name plus path, such as: /2015/06/04/aa.jpg * @param localPath Store at the local address* @return */ public boolean downloadFile(String filename,String localPath) { FTPClient ftp=new FTPClient(); try { ftp.connect(host, port); ftp.login(username, password); //Set the file encoding format ftp.setControlEncoding("UTF-8"); //There are two modes of ftp communication //The PORT (active mode) client opens a new port (>1024) and sends commands or transmits data through this port. During this period, the server only uses one port it opens, such as 21 //PASV (passive mode) client sends a PASV command to the server, the server opens a new port (>1024), and uses this port to transmit data with the client's port 21//The server needs to open the port from the server because the client is uncontrollable, firewall, etc., so the server needs to open the port, and the passive mode ftp.enterLocalPassiveMode(); //Set the transmission mode to stream mode ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); //Get the status code to determine whether the connection is successful if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new RuntimeException("FTP server refuses to connect"); } int index=filename.lastIndexOf("/"); //Get the path of the file String path=filename.substring(0, index); //Get the file name String name=filename.substring(index+1); //Judge whether the directory exists if(!ftp.changeWorkingDirectory(basePath+path)) { throw new RuntimeException("File path does not exist: "+basePath+path); } //Get all files in this directory FTPFile[] files=ftp.listFiles(); for (FTPFile file : files) { //Judge whether there is a target file //System.out.println("File name"+file.getName()+"---"+name); if(file.getName().equals(name)) { //System.out.println("File Found"); //If found, copy the target file to the local File localFile =new File(localPath+"/"+file.getName()); OutputStream out=new FileOutputStream(localFile); ftp.retrieveFile(file.getName(), out); out.close(); } } ftp.logout(); return true; } catch (Exception e) { throw new RuntimeException(e); } finally { if(ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { throw new RuntimeException(e); } } } } //If one of the two functions is used, the other needs to be commented on public static void main(String []args) { //Upload test--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- e.printStackTrace(); } finally { }*/ //Download test-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Specific use
Step 1: Configure spring to load properties files
applicationContext.xml
<context:property-placeholder location="classpath:*.properties"/> ftp.propertiesftp.host=192.168.100.77ftp.port=21ftp.username=ftpuserftp.password=ftp54321ftp.basePath=/home/ftpuser/
Step 2: Declare the tool class as a bean
xml method
<bean id="ftpUtil"> <property name="host" value="${ftp.host}"></property> <property name="port" value="${ftp.port}"></property> <property name="username" value="${ftp.username}"></property> <property name="password" value="${ftp.password}"></property> <property name="basePath" value="${ftp.basePath}"></property> </bean>Annotation method, component scanning
<context:component-scan base-package="com.cky.util"></context:component-scan>
Part 3: Injection and use
@Autowired private FtpUtil ftpUtil;
Summarize
The above is a summary of Spring FTP upload and download tool issues introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!