This article mainly introduces how to use the ftp tool provided by Apache toolset commons-net to upload and download files to the ftp server.
1. Preparation
Need to reference the commons-net-3.5.jar package.
Import using maven:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.5</version></dependency>
Manual download:
//www.VeVB.COM/softs/550085.html
2. Connect to FTP Server
/** * Connect to FTP Server * @throws IOException */public static final String ANONYMOUS_USER="anonymous";private FTPClient connect(){FTPClient client = new FTPClient();try{//Connect FTP Serverclient.connect(this.host, this.port);//Login if(this.user==null||"".equals(this.user)){//Login in client.login(ANONYMOUS_USER, ANONYMOUS_USER);} else{client.login(this.user, this.password);}//Set the file format client.setFileType(FTPClient.BINARY_FILE_TYPE);//Get the FTP Server reply int reply = client.getReplyCode();if(!FTPReply.isPositiveCompletion(reply)){client.disconnect();return null;}//Switch the working directory changeWorkingDirectory(client);System.out.println("===Connect to FTP: "+host+":"+port);}catch(IOException e){return null;}return client;}/** * Switch the working directory. When the remote directory does not exist, create the directory* @param client * @throws IOException */private void changeWorkingDirectory(FTPClient client) throws IOException{if(this.ftpPath!=null&&!"".equals(this.ftpPath)){Boolean ok = client.changeWorkingDirectory(this.ftpPath);if(!ok){//ftpPath does not exist, create the directory manually StringTokenizer token = new StringTokenizer(this.ftpPath,"////");while(token.hasMoreTokens()){String path = token.nextToken();client.makeDirectory(path);client.changeWorkingDirectory(path);}}}}/** * Disconnect the FTP connection* @param ftpClient * @throws IOException */public void close(FTPClient ftpClient) throws IOException{if(ftpClient!=null && ftpClient.isConnected()){ftpClient.logout();ftpClient.disconnect();}System.out.println("!!!DisconnectFTP connection: "+host+":"+port);} host: ftp server IP address
port: ftp server port
user: login user
password: When the login password is empty, use an anonymous user to log in.
ftpPath: ftp path, automatically created when the ftp path does not exist. If it is a multi-layer directory structure, it is necessary to create the directory iteratively.
3. Upload files
/** * Upload file* @param targetName Upload to ftp file name* @param localFile Local file path* @return */public Boolean upload(String targetName,String localFile){//Connect ftp serverFTPClient ftpClient = connect();if(ftpClient==null){System.out.println("Connect to FTP server["+host+":"+port+"] failed!");return false;}File file = new File(localFile);//Set the file name after upload if(targetName==null||"".equals(targetName)) targetName = file.getName();FileInputStream fis = null;try{long now = System.currentTimeMillis();//Start upload file fis = new FileInputStream(file);System.out.println(">>>Start upload file: "+file.getName());Boolean ok = ftpClient.storeFile(targetName, fis);if(ok){//Upload long successfully times = System.currentTimeMillis() - now;System.out.println(String.format(">>>>Uploaded successfully: size: %s, upload time: %d seconds", formatSize(file.length()), times/1000));} else//Upload failed System.out.println(String.format(">>>Upload failed: size: %s", formatSize(file.length())));}catch(IOException e){System.err.println(String.format(">>>Upload failed: size: %s", formatSize(file.length())));e.printStackTrace();return false;} finally{try{if(fis!=null) fis.close();close(ftpClient);}catch(Exception e){}}return true;}4. Download the file
/** * Download file* @param localPath Local storage path* @return */public int download(String localPath){// Connect to ftp serverFTPClient ftpClient = connect();if(ftpClient==null){System.out.println("Connect to FTP server["+host+":"+port+"] failed!");return 0;}File dir = new File(localPath);if(!dir.exists()) dir.mkdirs();FTPFile[] ftpFiles = null;try{ftpFiles = ftpClient.listFiles();if(ftpFiles==null||ftpFiles.length==0) return 0;}catch(IOException e){return 0;}int c = 0;for (int i=0;i<ftpFiles.length;i++){FileOutputStream fos = null;try{String name = ftpFiles[i].getName();fos = new FileOutputStream(new File(dir.getAbsolutePath()+File.separator+name));System.out.println("<<< Start downloading file: "+name); long now = System.currentTimeMillis();Boolean ok = ftpClient.retrieveFile(new String(name.getBytes("UTF-8"),"ISO-8859-1"), fos);if(ok){//Download successfully long times = System.currentTimeMillis() - now;System.out.println(String.format("<<<Download Successfully: Size: %s, Upload Time: %d Seconds", formatSize(ftpFiles[i].getSize()), times/1000));c++;} else{System.out.println("<<<Download Failed");}}catch(IOException e){System.err.println("<<<Download Failed");e.printStackTrace();} finally{try{if(fos!=null) fos.close();close(ftpClient);}catch(Exception e){}}} return c;}Format file size
private static final DecimalFormat DF = new DecimalFormat("#.##"); /** * Format file size (B, KB, MB, GB) * @param size * @return */ private String formatSize(long size){ if(size<1024){ return size + "B"; }else if(size<1024*1024){ return size/1024 + "KB"; }else if(size<1024*1024*1024){ return (size/(1024*1024)) + " MB"; }else{ double gb = size/(1024*1024*1024); return DF.format(gb)+" GB"; } }V. Test
public static void main(String args[]){ FTPTest ftp = new FTPTest("192.168.1.10",21,null,null,"/temp/2016/12"); ftp.upload("newFile.rar", "D:/ftp/TeamViewerPortable.rar"); System.out.println(""); ftp.download("D:/ftp/"); }result
===Connect to FTP: 192.168.1.10:21>>>Start upload file: TeamViewerPortable.rar>>>Uploaded successfully: Size: 5 MB, Upload time: 3 seconds!!!Disconnected FTP connection: 192.168.1.10:21===Connect to FTP: 192.168.1.10:21<<<Start download file: newFile.rar<<<Discovered successfully: Size: 5 MB, Upload time: 4 seconds!!!Disconnected FTP connection: 192.168.1.10:21
Summarize
The above is all the detailed explanation of Java's use of Apache toolset to implement ftp file transfer code, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!