今天被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