java操作FTP

引入依赖

        <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);
Java中,你可以使用第三方库如Apache Commons Net或者FTPClient4J来进行FTP(File Transfer Protocol)服务器的操作。以下是一个简单的示例,展示如何连接、上传、下载以及断开FTP连接: 首先,你需要在项目中添加相应的依赖。例如,对于Apache Commons Net,你可以在pom.xml中添加: ```xml <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency> ``` 然后,你可以使用以下代码片段进行基本操作: ```java import org.apache.commons.net.ftp.*; public class FTPOperations { private FtpClient client; public void connect(String host, int port, String user, String password) throws IOException { client = new FtpClient(); client.connect(host, port); client.login(user, password); } public void uploadFile(String localFilePath, String remoteFilePath) throws IOException { FileInputStream fis = new FileInputStream(localFilePath); client.storeFile(remoteFilePath, fis); fis.close(); } public void downloadFile(String remoteFilePath, String localFilePath) throws IOException { InputStream fis = client.retrieveFileStream(remoteFilePath); FileOutputStream fos = new FileOutputStream(localFilePath); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } fos.close(); fis.close(); } public void disconnect() throws IOException { client.logout(); client.disconnect(); } public static void main(String[] args) { try { FTPOperations ftp = new FTPOperations(); // 连接到FTP服务器 ftp.connect("ftp.example.com", 21, "username", "password"); // 执行上传、下载等操作 ftp.uploadFile("/path/to/local/file.txt", "/remote/file.txt"); ftp.downloadFile("/remote/file.txt", "/path/to/download/file.txt"); // 断开连接 ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值