用FtpClient实现文件下载(全目录不只是文件夹)

原文:https://blog.csdn.net/java2000_net/article/details/3718852

  • 需要用到的jar是
	<!-- FTP -->
<dependency>
	<groupId>commons-net</groupId>
	<artifactId>commons-net</artifactId>
	<version>3.6</version>
</dependency>
  • 具体代码如下
package com.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
 * @Author: YafengLiang
 * @Description:
 * @Date: Created in  16:40 2018/12/5
 */
public class FtpTest {
        private static final Logger logger = LoggerFactory.getLogger(FtpTest.class);
        static FTPClient ftpClient;
	    final static String HOST="192.168.6.88";
        final static int PORT=21;
        final static String USERNAME="user1";
        final static String PASSWORD="voicecyber@123";
        final static String LOCAL_DIRECTORY="F:/voicecyber/";

        public static void login() throws IOException{
            ftpClient = new FTPClient();
            ftpClient.connect(HOST,PORT);
            ftpClient.login(USERNAME, PASSWORD);
            //设置编码
            ftpClient.setControlEncoding("GBK");
            ftpClient.setBufferSize(8096);
        }

    /**
     * 判断给定的路径是文件还是文件夹
     * @param path
     * @return
     * @throws IOException
     */
        public static boolean isDirectory(String path) throws IOException{
            //如果是文件,就会返回false
            //如果文件夹或文件名中含有中文,这里要转换一下,不然会返回false
            return ftpClient.changeWorkingDirectory(new String(path.getBytes(),"ISO-8859-1"));
        }

    /**
     * 判断本地路径是否存在,不存在就创建路径
     * @param path
     */
    public static void makeDirs(String path){
            File localFile = new File(LOCAL_DIRECTORY+path);
            if(!localFile.exists()){
                localFile.mkdirs();
            }
        }

    /**
     * 下载单个文件
     * @param dir
     * @throws IOException
     */
    public static void downloadFile(String dir) throws IOException{
            File file = new File(LOCAL_DIRECTORY + dir);
            OutputStream os = new FileOutputStream(file);
            ftpClient.setControlEncoding("GBK");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //如果文件名中含有中文,retrieveFile文件时会找不到FTP上的文件,导致保存在本地的是一个空文件,所以也要转换一下
            ftpClient.retrieveFile(new String(file.getName().getBytes(),"ISO-8859-1"), os);
            os.close();
        }

    /**
     * 下载任务,递归调用,循环下载所有目录下的文件
     * @param path
     * @throws IOException
     */
    public static void doDownload(String path) throws IOException{
            //创建本地目录
            makeDirs(path);
            //切换工作目录
            ftpClient.changeWorkingDirectory(new String(path.getBytes(),"ISO-8859-1"));
            //获取目录下的文件列表
            String[] fileNames = ftpClient.listNames();
            //循环下载FTP目录下的文件
            for(String fname:fileNames){
                if(isDirectory(path+"/"+fname)){
                    //递归调用
                    doDownload(path+"/"+fname);
                }else{
                    //下载单个文件
                    downloadFile(path+"/"+fname);
                }
            }
        }

    /**
     * 实时同步ftp目录文件到本地
     */
    public static class MyRun implements Runnable{
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(10*1000);
                        logger.info("休息十秒。。。。。。");
                        doDownload("/");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
        public static void main(String[] args) throws IOException {
            //连接FTP服务器
            login();
            //全目录下载
            MyRun myRun = new MyRun();
            new Thread(myRun).start();
            //testUpload();
        }

     
  	 /**
     * ftp上传
     */
        public static void testUpload() {
            FTPClient ftpClient = new FTPClient();
            FileInputStream fis = null;

            try {
                ftpClient.connect("172.20.16.76",9500);
                ftpClient.login("lyc", "123456");

                JFileChooser fd = new JFileChooser();
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                SwingUtilities.updateComponentTreeUI(fd);
                fd.showOpenDialog(null);
                File srcFile = fd.getSelectedFile();
                //if(srcFile != null){}

                fis = new FileInputStream(srcFile);
                //设置上传目录
                ftpClient.changeWorkingDirectory("/img");
                //ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("GBK");
                //设置文件类型(二进制)
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.storeFile(srcFile.getName(), fis);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("FTP客户端出错!", e);
            } finally {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException("关闭FTP连接发生异常!", e);
                }
            }
        }

    }


  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Apache Commons Net 库中的 FTPClient 类来实现 Java FTP 递归下载文件的功能。下面是一个示例代码,可以下载 FTP 服务器上指定目录下的所有文件及其子目录下的所有文件和文件夹: ```java 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.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FtpDownloader { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String username = "username"; String password = "password"; String remoteDirPath = "/path/to/remote/directory"; String localDirPath = "/path/to/local/directory"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(username, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); downloadDirectory(ftpClient, remoteDirPath, localDirPath); ftpClient.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } private static void downloadDirectory(FTPClient ftpClient, String remoteDirPath, String localDirPath) throws IOException { FTPFile[] subFiles = ftpClient.listFiles(remoteDirPath); if (subFiles != null && subFiles.length > 0) { for (FTPFile ftpFile : subFiles) { String remoteFilePath = remoteDirPath + "/" + ftpFile.getName(); String localFilePath = localDirPath + "/" + ftpFile.getName(); if (ftpFile.isDirectory()) { // create the directory in local file system File localDir = new File(localFilePath); if (!localDir.exists()) { localDir.mkdir(); } // download the sub directory recursively downloadDirectory(ftpClient, remoteFilePath, localFilePath); } else { // download the file OutputStream outputStream = new FileOutputStream(localFilePath); ftpClient.retrieveFile(remoteFilePath, outputStream); outputStream.close(); } } } } } ``` 在上面的代码中,`downloadDirectory()` 方法递归地下载指定目录下的所有文件和文件夹。如果遇到子目录,它会在本地文件系统中创建一个对应的目录,并递归下载目录下的所有文件和文件夹。如果遇到普通文件,它会将其下载到本地文件系统中。 你需要将代码中的 `server`,`port`,`username`,`password`,`remoteDirPath` 和 `localDirPath` 替换为你自己的 FTP 服务器地址、端口、用户名、密码、远程目录和本地目录

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值