Java FTP按关键字批量下载文件

时间:2025-02-16 12:00:05
  • import .*;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • import ;
  • public class FTPBulkFileDownloader {
  • public static void downloadFiles(String server, int port, String user, String pass, String remoteDir, String saveDir, String keyword) throws IOException {
  • FTPClient ftpClient = new FTPClient();
  • try {
  • (server, port);
  • (user, pass);
  • ();
  • (FTP.BINARY_FILE_TYPE);
  • List<String> filesToDownload = getFilesToDownload(ftpClient, remoteDir, keyword);
  • for (String file : filesToDownload) {
  • String remoteFilePath = remoteDir + "/" + file;
  • String saveFilePath = saveDir + + file;
  • downloadFile(ftpClient, remoteFilePath, saveFilePath);
  • }
  • } finally {
  • if (()) {
  • ();
  • ();
  • }
  • }
  • }
  • private static List<String> getFilesToDownload(FTPClient ftpClient, String remoteDir, String keyword) throws IOException {
  • List<String> filesToDownload = new ArrayList<>();
  • FTPFile[] files = (remoteDir);
  • for (FTPFile file : files) {
  • if (() && ().contains(keyword)) {
  • (());
  • }
  • }
  • return filesToDownload;
  • }
  • private static void downloadFile(FTPClient ftpClient, String remoteFilePath, String saveFilePath) throws IOException {
  • InputStream inputStream = (remoteFilePath);
  • BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
  • FileOutputStream fileOutputStream = null;
  • try {
  • fileOutputStream = new FileOutputStream(saveFilePath);
  • int bytesRead;
  • byte[] buffer = new byte[1024];
  • while ((bytesRead = (buffer)) != -1) {
  • (buffer, 0, bytesRead);
  • }
  • ("File downloaded: " + saveFilePath);
  • } finally {
  • if (bufferedInputStream != null) {
  • ();
  • }
  • if (fileOutputStream != null) {
  • ();
  • }
  • ();
  • }
  • }
  • public static void main(String[] args) {
  • String server = "FTPIP";
  • //FTP端口
  • int port = 21;
  • //用户名
  • String user = "";
  • //密码
  • String pass = "";
  • //FTP文件目录
  • String remoteDir = "/FTP";
  • //本地文件存放目录
  • String saveDir = "/local";
  • //关键字
  • String keyword = "222";
  • try {
  • downloadFiles(server, port, user, pass, remoteDir, saveDir, keyword);
  • } catch (IOException e) {
  • ();
  • }
  • }
  • }