JAVA实现ftp文件的上传及下载

1、引入依赖包

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.*;

2、连接ftp服务器

   String server = "192.168.1.100";
        int port = 21;
        String user = "test";
        String password = "password";


        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);
            ftpClient.login(user, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
       } catch (IOException ex) {
            System.out.println("发生IO异常:" + ex.getMessage());
            ex.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

3、上传文件

// 上传文件
String localFileToUpload = "D:\\test\\file.txt";
String remoteFileToUpload = "/test/file.txt";
boolean uploadSuccess = uploadFile(ftpClient, localFileToUpload, remoteFileToUpload);
if (uploadSuccess) {
     System.out.println("文件上传成功!");
} else {
      System.out.println("文件上传失败!");
}


public static boolean uploadFile(FTPClient ftpClient, String localFilePath, String remoteFilePath) throws IOException {
        File localFile = new File(localFilePath);
        InputStream inputStream = new FileInputStream(localFile);
        try {
            return ftpClient.storeFile(remoteFilePath, inputStream);
        } finally {
            inputStream.close();
        }
    }

4、下载文件

 // 下载文件
 String remoteFilePath = "/test/file.txt";
 String localFilePath = "D:\\test\\other\\file.txt";
 boolean downloadSuccess = downloadFile(ftpClient, remoteFilePath, localFilePath);
 if (downloadSuccess) {
       System.out.println("文件下载成功!");
 } else {
       System.out.println("文件下载失败!");
 }

 public static boolean downloadFile(FTPClient ftpClient, String remoteFilePath, String localFilePath) throws IOException {
        File downloadFile = new File(localFilePath);
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
        try {
            return ftpClient.retrieveFile(remoteFilePath, outputStream);
        } finally {
            outputStream.close();
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code_Geo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值