English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article mainly introduces how to use Apache toolset commons-The ftp tool provided by net is used to upload and download files to the ftp server.
First, prepare
Need to refer to commons-net-3.5.jar package.
Use Maven to import:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.5</version> </dependency>
Manual download:
https://www.oldtoolbag.com/softs/550085.html
Second, 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 to FTP Server client.connect(this.host, this.port); //Login if(this.user==null||"".equals(this.user)){ //Use anonymous login client.login(ANONYMOUS_USER, ANONYMOUS_USER); } else{ client.login(this.user, this.password); } //Set file format client.setFileType(FTPClient.BINARY_FILE_TYPE); //Obtaining FTP Server response int reply = client.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)){ client.disconnect(); return null; } //Switch to working directory changeWorkingDirectory(client); System.out.println("===Connected to FTP:")+host+:"+port); } catch(IOException e){ return null; } return client; } /** * Switch to working directory, create the directory if the remote directory does not exist * @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, manually create the directory StringTokenizer token = new StringTokenizer(this.ftpPath,"\\",//"); while(token.hasMoreTokens()){ String path = token.nextToken(); client.makeDirectory(path); client.changeWorkingDirectory(path); } } } } /** * Disconnect 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("!!!Disconnected from FTP connection:")+host+:"+port); }
host: FTP server IP address
port: FTP server port
user: Login user
password: Login password
If the login user is empty, use anonymous user login.
ftpPath: FTP path, if the FTP path does not exist, it will be automatically created. If it is a multi-level directory structure, the directories need to be created iteratively.
III. Upload file
/** * Upload file * @param targetName FTP file name to upload * @param localFile Local file path * @return */ public Boolean upload(String targetName,String localFile){ //Connect to ftp server FTPClient ftpClient = connect(); if(ftpClient==null){ System.out.println("Connecting to FTP server["+host+:"+port+"]Failed!"); return false; } File file = new File(localFile); //Set upload file name after upload if(targetName==null||"".equals(targetName)) targetName = file.getName(); FileInputStream fis = null; try{ long now = System.currentTimeMillis(); //Start uploading file fis = new FileInputStream(file); System.out.println(">>>Start uploading file: "+); Boolean ok = ftpClient.storeFile(targetName, fis); if(ok){ //Upload successful long times = System.currentTimeMillis(); - now; System.out.println(String.format(">>>Upload successful: 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; }
Four, download file
/** * Download file * @param localPath Local storage path * @return */ public int download(String localPath){ // Connect to ftp server FTPClient ftpClient = connect(); if(ftpClient==null){ System.out.println("Connecting 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("<<<Starting to download file:");+name); long now = System.currentTimeMillis(); Boolean ok = ftpClient.retrieveFile(new String(name.getBytes("UTF-8"),"ISO-8859-1"), fos); if(ok){ //Download successful long times = System.currentTimeMillis(); - now; System.out.println(String.format("<<<Download successful: 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){ " B";1024{ " KB"; + return size }1024*1024{ " KB";/1024 + else if(size< }1024*1024*1024{ return (size/(1024*1024)) + " MB"; }else{ double gb = size/(1024*1024*1024); return DF.format(gb)+" GB"; } }
5. 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
=== Connected to FTP:192.168.1.10:21 >>> Start uploading file: TeamViewerPortable.rar >>> Upload successful: size:5 MB, upload time:3second !!! Disconnect FTP connection:192.168.1.10:21 === Connected to FTP:192.168.1.10:21 <<< Start downloading file: newFile.rar <<< Download successful: size:5 MB, upload time:4second !!! Disconnect FTP connection:192.168.1.10:21
Summary
This is the full explanation of the code for implementing FTP file transfer using Apache tools in Java, which I hope will be helpful to everyone. Those who are interested can continue to read other related topics on this site, and welcome to leave comments if there are any shortcomings. Thank you for your support to this site!
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)