ftp获取指定中文目录时,找不到路径
工作中需要通过连接ftp服务获取ftp服务器上指定目录下的文件
以下是我通过各个地方找到的解决方法但是还是中文目录下的文件还是获取不了
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class FTPClientExample {
public static void main(String[] args) {
String server = "your_ftp_server";
int port = 21;
String username = "your_username";
String password = "your_password";
String remotePath = "/path/to/your/directory"; // 指定的路径,可以是中文路径
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 设置字符编码,处理中文路径
ftpClient.setControlEncoding("UTF-8");
// 编码中文路径
String encodedPath = encodePath(remotePath);
// 转到指定路径
if (ftpClient.changeWorkingDirectory(encodedPath)) {
// 获取目录下的文件和子目录
FTPFile[] files = ftpClient.listFiles();
for (FTPFile file : files) {
System.out.println(file.getName());
}
} else {
System.out.println("指定路径不存在");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 对路径进行编码
private static String encodePath(String path) throws UnsupportedEncodingException {
return URLEncoder.encode(path, "UTF-8").replace("+", "%20");
}
}
解决方法
使用new String(encodedPath.getBytes(“UTF-8”), “iso-8859-1”) 将路径从UTF-8转换为ISO-8859-1,可以解决中文路径在FTP服务器上的问题。这种方法在一些FTP服务器上确实是有效的,因为一些FTP服务器可能要求路径以ISO-8859-1编码表示