使用common-nets.jar FTPClient解决文件名中文乱码!
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTP;
/**
* FTP上传文件
* @author 张明亮
*
*/
public class FtpClientUtil {
private FTPClient ftpClient;
private String hostname;
private int port;
private String password;
private String username;
/**
* @param hostname 服务器地址
* @param port 服务器端口
* @param username 服务器用户名
* @param password 服务器密码
*/
public FtpClientUtil(String hostname,int port,String username, String password){
this.hostname = hostname;
this.port = port;
this.password = password;
this.username = username;
ftpClient = new FTPClient();
}
/**
* FTPClient连接
* @param hostname 服务器地址
* @param port 服务器端口
* @return
* @throws SocketException
* @throws IOException
*/
private boolean connectServer(String hostname, int port) throws SocketException, IOException{
this.ftpClient.connect(hostname, port);
return this.ftpClient.isConnected();
}
/**
* FTPClient登陆
* @param username 服务器用户名
* @param password 服务器密码
* @return
* @throws IOException
*/
private boolean login(String username, String password) throws IOException{
return this.ftpClient.login(username, password);
}
/**
* 通过输入流上传本地文件
* @param fileName 上传到服务器后文件名称
* @param inputStream 本地文件流
* @param remotePath 服务器路径
* @return 返回上传成功标志
* @throws SocketException
* @throws IOException
*/
public boolean uploadFile(String fileName, InputStream inputStream, String remotePath) throws SocketException, IOException{
boolean flag = false;
if(this.connectServer(this.hostname, this.port) && this.login(this.username, this.password)){
this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //使用二进制流上传文件
this.ftpClient.changeWorkingDirectory(remotePath); //跳转到服务器对应目录
flag = this.ftpClient.storeFile(fileName+".bak", inputStream);
if(flag){
this.ftpClient.rename(fileName+".bak", fileName); //修改文件名称
}
}
return flag;
}
/**
* @return
*/
public FTPClient getFtpClientInstance(){
return ftpClient;
}
/**
* FTOClient 连接
* @throws IOException
*/
public void disposeFtpClient() throws IOException{
if(this.ftpClient != null){
if(this.ftpClient.isConnected())
this.ftpClient.disconnect();
this.ftpClient = null;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
本文介绍了一个基于Commons Net库实现的FTP客户端工具类,该工具类能够解决中文文件名上传时出现的乱码问题。通过设置服务器地址、端口、用户名及密码等参数初始化客户端,并提供文件上传功能,支持指定远程路径和文件名。
2607





