使用Apache Commons FTP库从多目录下载文件的问题
Solution for Downloading Images from Specific FTP Directories (Apache Commons Net)
Got it, let's tackle this problem exactly how you described—staying rooted in the FTP server's root directory, targeting those specific subfolders, and pulling all images using Apache Commons Net. Here's a straightforward, practical implementation:
Core Approach
- Define all your target image directories as absolute paths (since we're not switching directories)
- For each directory, use
FTPClient.listFiles()with the full path to fetch all contained files - Filter out non-image files (tweak the allowed extensions to match your needs)
- Download each valid image to your local storage using
FTPClient.retrieveFile()
Full Code Example
import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.List; public class FTPImageDownloader { public static void main(String[] args) { // FTP server configuration String ftpServer = "your-ftp-host.com"; int ftpPort = 21; String ftpUser = "your-username"; String ftpPass = "your-password"; String localSavePath = "/your/local/save/folder"; // List of absolute target directories on the FTP root List<String> targetFtpDirs = Arrays.asList( "/iTable/imgprod", "/iTable/imgcat", "/iTable/imgmainmen", "/iTable/imgsubmen", "/iTable/standBy" ); // Supported image file extensions (adjust as needed) List<String> imageExtensions = Arrays.asList(".jpg", ".jpeg", ".png", ".gif"); FTPClient ftpClient = new FTPClient(); try { // Connect and authenticate ftpClient.connect(ftpServer, ftpPort); ftpClient.login(ftpUser, ftpPass); ftpClient.enterLocalPassiveMode(); // Avoid firewall issues ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // Critical for image integrity // Ensure local save directory exists File localDir = new File(localSavePath); if (!localDir.exists()) { localDir.mkdirs(); } // Process each target directory for (String ftpDir : targetFtpDirs) { System.out.println("Scanning directory: " + ftpDir); FTPFile[] files = ftpClient.listFiles(ftpDir); if (files == null || files.length == 0) { System.out.println("No files found in " + ftpDir); continue; } // Download valid images for (FTPFile file : files) { if (!file.isFile()) continue; // Skip subdirectories String fileName = file.getName(); boolean isImage = imageExtensions.stream() .anyMatch(ext -> fileName.toLowerCase().endsWith(ext)); if (isImage) { String remoteFilePath = ftpDir + "/" + fileName; String localFilePath = localSavePath + "/" + fileName; try (OutputStream outputStream = new FileOutputStream(localFilePath)) { boolean downloadSuccess = ftpClient.retrieveFile(remoteFilePath, outputStream); if (downloadSuccess) { System.out.println("Downloaded: " + remoteFilePath); } else { System.out.println("Failed to download: " + remoteFilePath); } } catch (IOException e) { System.err.println("Error downloading " + fileName + ": " + e.getMessage()); } } } } } catch (IOException e) { System.err.println("FTP connection error: " + e.getMessage()); } finally { // Clean up connection try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { System.err.println("Error closing FTP connection: " + e.getMessage()); } } } }
Key Details to Note
- Binary File Type: Always set
setFileType(FTPClient.BINARY_FILE_TYPE)—this prevents image corruption that can happen with default ASCII mode. - Passive Mode:
enterLocalPassiveMode()is recommended for most networks to avoid being blocked by firewalls. - Local Directory Check: The code creates the local save folder if it doesn't exist, so you don't have to pre-create it manually.
- Filter Flexibility: Adjust the
imageExtensionslist to include any other image formats you need (like.bmpor.webp). - Error Handling: Basic error handling is included, but you can extend it (e.g., add retry logic for failed downloads) based on your requirements.
内容的提问来源于stack exchange,提问作者Jack Moe
相关产品推荐
相关产品推荐

