Java使用apache commons连接ftp修改ftp文件名失败原因

使用Apache Commons的FtpClient修改FTP文件名时遇到问题,尤其是涉及中文名称时。通过在修改前对文件名进行编码转换,可以解决这个问题。同样,对于上传、下载、删除和检查文件/文件夹存在等操作,如果文件名包含中文,也建议先进行编码处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天被ftp上中文名修改坑了好久

项目用的是 apache commons 里的 FtpClient 实现的对ftp文件的上传下载操作,今天增加了业务要修改ftp上的文件名,然后就一直的报错,问题是它修改名字的方法只返回一个boolean,没有异常,这就很蛋疼了,找了好久才发现是中文的名字的原因

改名

直接上代码

package net.codejava.ftp;

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;

public class FTPRenamer {

    public static void main(String[] args) {
        String server = "www.ftpserver.com";
        int port = 21;
        String user = "username";
        String pass = "password";

        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);
            ftpClient.login(user, pass);

            // renaming directory
            String oldDir = "/photo";
            String newDir = "/photo_2012";

            boolean success = ftpClient.rename(oldDir, newDir);
            if (success) {
                System.out.println(oldDir + " was successfully renamed to: "
                        + newDir);
            } else {
                System.out.println("Failed to rename: " + oldDir);
            }

            // renaming file
            String oldFile = "/work/error.png";
            String newFile = "/work/screenshot.png";

            success = ftpClient.rename(oldFile, newFile);
            if (success) {
                System.out.println(oldFile + " was successfully renamed to: "
                        + newFile);
            } else {
                System.out.println("Failed to rename: " + oldFile);
            }

            ftpClient.logout();
            ftpClient.disconnect();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.logout();
                    ftpClient.disconnect();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

如果修改的名字里没有中文,用上面的代码就够了,但如果有中文就要对文件名进行转码了,转码代码如下

// renaming file
String oldFile = "/work/你好.png";
String newFile = "/work/世界.png";

success = ftpClient.rename(
    new String(oldFile.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1),
    new String(newFile.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)
);

这样再修改名字就没有问题了

顺便记录一下上传、下载、删除、检查文件是否存在,同样的,如果有中文名,最好先转一下码再进行操作

上传

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import jav
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值