FTP服务之Java操作FTP服务器下载文件的两种方式

FTP服务之Java操作FTP服务器下载文件的两种方式

注意:如果fpt服务中没有建立目录, 则默认文件目录为根目录也即/,否则按具体目录进行操作,如: /demo
FTP服务搭建查看博文 FTP服务之WindowsServer2019中搭建私有FTP服务器

1. 使用Apache commons-net工具包

1. 引入commons-net依赖

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

2. 操作案例

1. 单文件下载

@Test
    public void downLoadOne() {
        String server = "192.168.31.252";
        int port = 21;
        String user = "anonymous";
        String password = "";
        String remoteFile = "/demo/xxx说明书.pdf";
        String localFile = "F:\\ftpDownlaod\\newAAA.pdf";

        FTPClient ftpClient = new FTPClient();
        OutputStream outputStream = null;

        try {
            ftpClient.connect(server, port);
            ftpClient.login(user, password);
            ftpClient.enterLocalPassiveMode();
            outputStream = Files.newOutputStream(Paths.get(localFile));
            // ftp默认使用ISO-8859-1编码格式,所以这里需要转换为ISO-8859-1,“解决文件名为中文时,下载后为空文件的问题”
            String remoteFileName = new String(remoteFile.getBytes("GBK"), StandardCharsets.ISO_8859_1);
            ftpClient.retrieveFile(remoteFileName, outputStream);
        } catch (IOException ex) {
            System.out.println("DownLoad Error: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                ftpClient.disconnect();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

2. 切换到指定目录批量下载文件

   @Test
    public void batchDownLoadFileFromFtp() {
        FTPClient client = new FTPClient();
        try {
            //设置主机与端口
            client.connect("192.168.31.252", 21);
            //设置用户名及密码,这里以匿名用户登录为例,根据需求改为自己的用户名及密码
            client.login("anonymous", "");
            System.out.println("FTP服务器文件编码===>>" + client.getControlEncoding());
            int reply = client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                client.disconnect();
                System.out.println("Login Error,Please check if your username or password is correct");
                return;
            }
            client.setControlEncoding("GBK");
            System.out.println("设置后的文件编码:" + client.getControlEncoding());
            client.enterLocalPassiveMode();
            //切换到demo目录下
            client.changeWorkingDirectory("demo");
            System.out.println("---------------------------------------");
            String[] names;
            names = client.listNames();
            for (String name : names) {
                System.out.println(name);
            }
            System.out.println("ftp服务中,demo目录中的所有文件:" + Arrays.toString(names));

            System.out.println("---------------------------------------");

            FTPFile f = client.listFiles()[0];
            System.out.println("getLink===>" + f.getLink());
            //切换到根目录下
            client.changeWorkingDirectory("/");
            String path = "/demo";

            client.setBufferSize(1024);
            client.setFileType(FTP.BINARY_FILE_TYPE);
            client.enterLocalPassiveMode();
            //切换到demo目录下获取此目录中所有的文件,并进行一个下载
            client.changeWorkingDirectory(path);
            FTPFile[] fs = client.listFiles();
            for (FTPFile ff : fs) {
                String outFileName = ff.getName();
                System.out.println(outFileName);
                //本地目录文件不需要编码
                File localFile = new File("F:\\ftpDownlaod\\" + ff.getName());
                OutputStream fos = Files.newOutputStream(localFile.toPath());
                // ftp默认使用ISO-8859-1编码格式,所以这里需要转换为ISO-8859-1,“解决文件名为中文时,下载后为空文件的问题”
                String localFileName = new String(ff.getName().getBytes("GBK"), StandardCharsets.ISO_8859_1);
                client.retrieveFile(localFileName, fos);
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

2. 使用Hutool工具

Hutool对FTP客户端基于Apache Commons Net做了进一步的封装。

文档地址:扩展(Hutool-extra) - FTP封装-Ftp

1. 引入依赖

<dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.10.0</version>
        </dependency>             
<dependency>
                    <groupId>cn.hutool</groupId>
                    <artifactId>hutool-all</artifactId>
                    <version>5.8.23</version>
                </dependency>

2. 操作案例

1. 文件下载

目前存在的问题: 如果文件名称是中文,则下载后的文件大小为0


@Test
    public void ftpServerTestByAnonymousOne() {
        Ftp ftp = new Ftp("192.168.31.252", 21);
        String downLoadPath = "/demo";
        String fileName = "demo.pdf";
        String outputPath = "F:\\ftpDownlaod";
        ftp.download(downLoadPath, fileName, new File(outputPath));

        //关闭连接
        try {
            ftp.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //FtpUtil.downloadFile(host, port, user, password, remotePath, localPath);
    }


    @Test
    public void ftpServerTestByAnonymousTwo() throws UnsupportedEncodingException {
        Ftp ftp = new Ftp("192.168.31.252", 21, "anonymous", "", StandardCharsets.UTF_8);
        String downLoadPath = "/demo";
        String fileName = "数据迁移最佳实践.pdf";
        //String remoteFileName = new String(fileName.getBytes("utf-8"),"ISO-8859-1");
        String outputPath = "F:\\ftpDownlaod\\xxx.pdf";
        ftp.download(downLoadPath, fileName, new File(outputPath));
        //关闭连接
        try {
            ftp.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //FtpUtil.downloadFile(host, port, user, password, remotePath, localPath);
    }
  • 14
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用以下两种方式实现跨服务器上传下载文件: 1. 使用FTP协议:FTP协议是一种文件传输协议,可以实现跨服务器上传下载文件Java中可以使用Apache Commons Net库来实现FTP文件传输。示例代码如下: ``` import org.apache.commons.net.ftp.*; public class FtpExample { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String user = "username"; String pass = "password"; FTPClient client = new FTPClient(); try { client.connect(server, port); client.login(user, pass); client.enterLocalPassiveMode(); String remoteFile = "/path/to/remote/file"; File localFile = new File("/path/to/local/file"); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile)); boolean success = client.retrieveFile(remoteFile, outputStream); outputStream.close(); if (success) { System.out.println("File downloaded successfully."); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (client.isConnected()) { client.logout(); client.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 2. 使用HTTP协议:HTTP协议也可以用于文件传输,可以通过HTTP的POST和GET请求来实现文件上传和下载Java中可以使用Apache HttpClient库来实现HTTP文件传输。示例代码如下: ``` import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpExample { public static void main(String[] args) { HttpClient httpClient = HttpClients.createDefault(); // 文件上传 HttpPost httpPost = new HttpPost("http://example.com/upload"); FileBody fileBody = new FileBody(new File("/path/to/local/file")); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", fileBody); httpPost.setEntity(builder.build()); try { HttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity()); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } // 文件下载 HttpGet httpGet = new HttpGet("http://example.com/download?file=/path/to/remote/file"); try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("/path/to/local/file")); byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); inputStream.close(); EntityUtils.consume(entity); System.out.println("File downloaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值