引入依赖

        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.8.0</version>
        </dependency>

常用方法

方法名参数说明作用返回值
connect(String hostname, int port)hostname: FTP服务器的主机名或IP地址;port: 端口号连接到指定的FTP服务器建立与FTP服务器的连接void
login(String username, String password)username: 用户名;password: 密码使用提供的用户名和密码登录FTP服务器登录到FTP服务器boolean (成功为true, 失败为false)
disconnect()断开与FTP服务器的连接关闭连接并释放资源void
changeWorkingDirectory(String pathname)pathname: 目标目录路径改变当前的工作目录切换到指定的目录boolean (成功为true, 失败为false)
makeDirectory(String pathname)pathname: 要创建的目录路径创建一个新的目录在当前目录下创建新目录boolean (成功为true, 失败为false)
removeDirectory(String pathname)pathname: 要删除的目录路径删除一个空目录移除指定的空目录boolean (成功为true, 失败为false)
deleteFile(String pathname)pathname: 要删除的文件路径删除一个文件移除指定的文件boolean (成功为true, 失败为false)
rename(String fromName, String toName)fromName: 当前文件名;toName: 新文件名重命名文件或目录更改文件或目录的名称boolean (成功为true, 失败为false)
storeFile(String remote, InputStream local)remote: 服务器上的文件路径;local: 输入流上传文件到FTP服务器将本地文件上传至服务器boolean (成功为true, 失败为false)
retrieveFile(String remote, OutputStream local)remote: 服务器上的文件路径;local: 输出流下载文件从FTP服务器将服务器文件下载至本地boolean (成功为true, 失败为false)
listFiles(String pathname)pathname: 目录路径列出指定目录下的文件列表获取目录内容FTPFile[] (文件对象数组)
printWorkingDirectory()打印当前工作目录获取当前的工作目录路径String
setFileType(int fileType)fileType: 文件类型(如ASCII或二进制)设置传输文件的类型指定文件传输模式void
enterLocalPassiveMode()进入被动模式设置数据连接为被动模式void
enterLocalActiveMode()进入主动模式设置数据连接为主动模式void
logout()注销当前用户退出登录状态boolean (成功为true, 失败为false)

org.apache.commons.net.ftp.FTPClient 类提供了许多其他方法来处理各种FTP操作。此外,实际返回值可能会根据FTP服务器的响应而有所不同

FTPClient

java链接FTP文件使用的是FTPClient或者FTPSClient,先确认你是FTP文件服务器还是FTPS
实例

    @Test
    public void testFile3() throws IOException {
        //存放图片的文件夹
        String url="C:\\Users\\w4523\\Desktop\\测试图片";
        // FTP服务器地址
        String server = "";
        int port = 21; // FTPS端口
        String user = "";
        String password = "";
        //远程目录,文档要求上传后转移到该目录
        String swapfiles = "/swapfiles";
        //远程目录,文档上传后的临时目录
        String tmp="/tmp";

        FTPClient ftpClient = new FTPClient();
        // 连接到服务器
        ftpClient.connect(server, port);
        // 登录
        if(ftpClient.login(user, password)){
            log.info("登录成功...");
            try {
                ftpClient.enterLocalPassiveMode();
                //设置文件传输模式为二进制模式
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                //读取文件夹
                File dir = new File(url);
                if (dir.isDirectory()) {
                    //获取文件夹下的所有文件名
                    String[] children = dir.list();
                    if (children != null) {
                        for (String child : children) {
                            //创建文件对象
                            File file = new File(dir, child);
                            // 输出文件的全路径
                            System.out.println("文件全路径"+file.getCanonicalPath());
                            //获取文件输入流
                            InputStream inputStream = getFileInputStream("file:///"+file.getCanonicalPath());
                            //切换到临时目录,不存在的话返回false
                            boolean changResult = ftpClient.changeWorkingDirectory(tmp);
                            if(!changResult){
                                //创建临时目录
                                if(ftpClient.makeDirectory(tmp)){
                                    //切换到临时目录
                                    changResult = ftpClient.changeWorkingDirectory(tmp);
                                }
                            }
                            if(changResult){
                                //上传文件,child:文件名。inputStream:文件输入流
                                if(ftpClient.storeFile(child, inputStream)){
                                    //上传成功以后切换到目标目录
                                    boolean changeResult = ftpClient.changeWorkingDirectory(swapfiles);
                                    if(!changeResult){
                                        //目标目录不存在,创建目标目录
                                        if(ftpClient.makeDirectory(swapfiles)){
                                            //切换到目标目录
                                            changeResult = ftpClient.changeWorkingDirectory(swapfiles);
                                        }
                                    }
                                    if(changeResult){
                                        //复制文件到目标目录
                                        ftpClient.rename(tmp+"/"+child,swapfiles+"/"+child);
                                    }
                                    log.info("文件上传成功");
                                }else{
                                    log.error("文件上传失败");
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                log.info("退出ftp服务器...");
                ftpClient.logout();
                log.info("断开ftp连接...");
                ftpClient.disconnect();
            }
        }else{
            log.info("登录失败...");
        }
    }

    private static InputStream getFileInputStream(String fileUrl) throws Exception {
        URL url = new URL(fileUrl);
        URLConnection urlConnection = url.openConnection();
        return urlConnection.getInputStream();
    }

其它

报错java.lang.RuntimeException: java.net.MalformedURLException: unknown protocol: c

指定本地路径的时候要用前缀file:///
在这里插入图片描述

报错FTPSClient提示530 Please login with USER and PASS

这句代码报错,确认你的文件服务器类型,是FTPS还是FTP,要用对应的对象,FTPClient或者FTPSClient,否则connect就会报这个错误

// 连接到服务器
ftpClient.connect(server, port);
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐