Ftp实现文件的上传下载(commons-net依赖)(解决ftp上传下载文件乱码)

首先我们引入commons-net依赖,这是个基于Socket的ftp依赖,API在
http://commons.apache.org/proper/commons-net/apidocs/index.html

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

登录方式为

//验证登录
        try {
            FTPClient ftp = new FTPClient();
            ftp.connect(ip, port);
            System.out.println(ftp.login(name, pwd));
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setCharset(Charset.forName("UTF-8"));
            ftp.setControlEncoding("UTF-8");

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

乱码原因是字符编码问题,在ftpcilent处定义下就好

ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setCharset(Charset.forName(“UTF-8”));
ftp.setControlEncoding(“UTF-8”);
获取文件列表方式:

FTPClient f = new FTPClient();
f.connect(server);
f.login(username, password);
FTPFile[] files = f.listFiles(directory);

FTPClient f = new FTPClient();
f.connect(server);
f.login(username,password);
FTPListParseEngine engine =
        f.initiateListParsing("com.whatever.YourOwnParser", directory);
// FTPListParseEngine engine = f.initiateListParsing(directory);
while(engine.hasNext()){
    FTPFile[] files = engine.getNext(25);  // "page size" you want
    //do whatever you want with these files, display them, etc.
    //expensive FTPFile objects not created until needed.
}

上传:

public void putFile(File file) {
        try {
            OutputStream os = ftp.storeFileStream(file.getName());
            FileInputStream fis = new FileInputStream(file);

            byte[] b = new byte[1024];
            int len = 0;
            while ((len = fis.read(b)) != -1) {
                os.write(b, 0, len);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}


public void putFiles(File srcFile) {
        try {
            if (!srcFile.exists()) {
                srcFile.mkdirs();
            }
            for (File file : srcFile.listFiles()) {
                if (file.isDirectory()) {
                    putFiles(file);
                } else {
                    putFile(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
}

下载:

public void getFile(String fileName, File file) {
        try {
            //将ftp的file路径下的"fileName"文件下载到本地目录文件夹下面,并重命名为"fileName"
            ftp.retrieveFile(fileName, new FileOutputStream(new File(file.getPath() + "\\" + fileName)));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


public void getFiles() {
        List<String> fileNameList = getFilesName();
        try {
            ReadConfig readConfig = new ReadConfig();
            DateUtil dateUtil = new DateUtil();
            File toFile = new File(readConfig.getTempPath() + "\\" + dateUtil.getDay() + "12");
            if (!toFile.exists()) {
                toFile.mkdirs();
            }
            for (int i = 0; i < fileNameList.size(); i++) {
                getFile(fileNameList.get(i), toFile);
                System.out.println(fileNameList.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

测试代码:

//    public static void main(String args[]) {
//        FTPUtil ftpUtil = new FTPUtil("172.18.66.209",18200,"admin","1234-123");
//        ftpUtil.getFilesName();
//        ftpUtil.getFiles();
//        File file = new File("D:\\thundersource\\2020051112");
//        ftpUtil.putFiles(file);
//        ftpUtil.putFile(file);
//        //ftpUtil.putFile();
//        ftpUtil.getFile();
//    }

需要注意的是,当使用org.apache.commons.net.ftp.FTPClient通过协议SSH2进行SFTP连接时会报Could not parse response code.Server Reply: SSH-2.0-OpenSSH_5.3,原因是它不支持这种方式的连接(使用FTPSClient的SSL也是不行的)。,我们需要使用com.jcraft.jsch.JSch提供的SSH解决方法,
详情请看https://blog.csdn.net/oLengYueHun/article/details/106098501

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Apache Commons Net库可以轻松地实现FTP上传和下载的功能。下面是一个简单的示例代码,演示了如何使用该库进行FTP文件上传和下载: 1. 导入Apache Commons Net库 下载Apache Commons Net库并将其添加到Android项目的构建路径中。 2. FTP连接 在执行FTP上传和下载之前,需要建立FTP连接。以下是如何建立一个FTP连接的示例代码: ```java // 创建FTP客户端对象 FTPClient ftpClient = new FTPClient(); try { // 连接FTP服务器 ftpClient.connect("ftp.example.com", 21); // 登录FTP服务器 ftpClient.login("username", "password"); // 设置文件类型为二进制类型 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { e.printStackTrace(); } ``` 3. FTP上传 以下是如何使用Apache Commons Net库进行FTP文件上传的示例代码: ```java // 创建FTP客户端对象 FTPClient ftpClient = new FTPClient(); try { // 连接FTP服务器 ftpClient.connect("ftp.example.com", 21); // 登录FTP服务器 ftpClient.login("username", "password"); // 设置文件类型为二进制类型 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 上传文件 File file = new File("/path/to/local/file"); InputStream inputStream = new FileInputStream(file); ftpClient.storeFile("/remote/path/file.txt", inputStream); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } ``` 4. FTP下载 以下是如何使用Apache Commons Net库进行FTP文件下载的示例代码: ```java // 创建FTP客户端对象 FTPClient ftpClient = new FTPClient(); try { // 连接FTP服务器 ftpClient.connect("ftp.example.com", 21); // 登录FTP服务器 ftpClient.login("username", "password"); // 设置文件类型为二进制类型 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 下载文件 File file = new File("/path/to/local/file"); OutputStream outputStream = new FileOutputStream(file); ftpClient.retrieveFile("/remote/path/file.txt", outputStream); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } ``` 注意:在完成FTP操作后,需要关闭FTP连接: ```java // 关闭FTP连接 ftpClient.logout(); ftpClient.disconnect(); ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值