FTP 文件上传 解决中文乱码

本文介绍了一个基于Commons Net库实现的FTP客户端工具类,该工具类能够解决中文文件名上传时出现的乱码问题。通过设置服务器地址、端口、用户名及密码等参数初始化客户端,并提供文件上传功能,支持指定远程路径和文件名。

使用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

 }

}

评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值