package com.ftp.demo; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import java.io.*; public class FtpDemo { public static void main(String[] args) { FTPClient ftpClient = new FTPClient(); String server = "url"; int port = 21; String username = "user"; String password = "123"; try { // 连接到FTP服务器 ftpClient.connect(server, port); ftpClient.login(username, password); // 设置文件传输模式为二进制 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (ftpClient.getReplyCode() > 0) { String dirs = "/filesync"; ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(dirs); FTPFile[] ftpFiles = ftpClient.listFiles(); for (int i = 0; i < ftpFiles.length; i++) { FTPFile ftpFile = ftpFiles[i]; System.out.println(ftpFile.getName()); InputStream inputStream = ftpClient.retrieveFileStream(dirs + File.separator + ftpFile.getName()); if (inputStream == null) { continue; } BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String s=null; while ((s= reader.readLine())!=null){ System.out.println(s); } System.out.println("ftpFile.getName() end."); inputStream.close(); reader.close(); ftpClient.completePendingCommand(); } } // 断开连接 ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
maven依赖
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.8.0</version> </dependency>