当前位置:编程学习 > JAVA >>

FTP上传文件中文文件名就乱码

    我已经搞了2天了,上传的ftp文件一遇到中文文件名就是乱码:源文件见下,我觉得在OutputStream os = ftpClient.put("您好.mp3");这里应该对文件名编码,但是试了好多种编码都不行,在线跪求………………


FileInputStream stream = new FileInputStream("您好.mp3");
ByteArrayOutputStream fileByte = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = stream.read(b)) != -1){
fileByte.write(b, 0, n);
}
FtpClient ftpClient = null;
BufferedOutputStream bos = null;
ftpClient = new FtpClient();
ftpClient.openServer(ftpServerIP, ftpServerPort);
ftpClient.login(ftpUserName, ftpPassword);
ftpClient.binary();
OutputStream os = ftpClient.put("您好.mp3");
bos = new BufferedOutputStream(os);
bos.write(fileByte.toByteArray(), 0, fileByte.size());
bos.close();
ftpClient.closeServer();
--------------------编程问答-------------------- 首先   ftp 最好不要有  中文  的文件名字存在       

如果非得中文的  你首先 要先确定   ftp 服务器端  支不支持   中文字符集  确定支持之后 再回来检查代码 --------------------编程问答--------------------
引用 1 楼 sjlzcj 的回复:
首先 ftp 最好不要有 中文 的文件名字存在  

如果非得中文的 你首先 要先确定 ftp 服务器端 支不支持 中文字符集 确定支持之后 再回来检查代码


怎么让ftp服务器端支持中文字符集? --------------------编程问答-------------------- 看你用的什么ftpclient,我用的是org.apache.commons.net.ftp.FTPClient

ftp.connect(ip, port);
//下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");

//如果采用默认端口,可以使用ftp.connect(url) 的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    return success;
}

//ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
chgDir=ftp.changeWorkingDirectory(new String(remotePath.getBytes(),"ISO-8859-1"));
if (chgDir) {
    FTPFile[] fs = ftp.listFiles();

    for (int i = 0; i < fs.length; i++) {
        FTPFile ff = fs[i];
        if (ff.getName().equals(fileName)) {

            File localFile = new File(localPath + File.separator + ff.getName());
            OutputStream is = new FileOutputStream(localFile);

            //注意此处retrieveFile的第一个参数由GBK转为ISO-8859-1编码。否则下载后的文件内容为空。
            //原因可能是由于aix系统默认的编码为ISO-8859-1
            ftp.retrieveFile(new String(ff.getName().getBytes("GBK"), "ISO-8859-1"), is);
            is.close();
        }
    }
}

ftp.logout();
--------------------编程问答-------------------- 楼主问题解决了没有啊?我也是遇到相同的问题了
估计楼主也是用的sun.net.ftp.FtpClient吧   问题解决了的话也告诉我是怎么解决的啊? --------------------编程问答--------------------
引用 4 楼 kkkmoving 的回复:
楼主问题解决了没有啊?我也是遇到相同的问题了
估计楼主也是用的sun.net.ftp.FtpClient吧 问题解决了的话也告诉我是怎么解决的啊?

就是sun.net.ftp.FtpClient,不过后来改成org.apache.commons.net.ftp.FTPClient,还添加了ftpClient.setControlEncoding("GBK");可惜一样中文文件名就乱码……
--------------------编程问答-------------------- 搂主,你的服务器是否支持中文呢?你在你的服务器上直接建立一个中文文件或者目录试试,如果是系统不支持中文,那就要从系统方面考虑了,............ --------------------编程问答--------------------
引用 6 楼 wula0010 的回复:
搂主,你的服务器是否支持中文呢?你在你的服务器上直接建立一个中文文件或者目录试试,如果是系统不支持中文,那就要从系统方面考虑了,............


已经证实服务器支持中文! --------------------编程问答-------------------- 今天在工作上也遇到了此问题,这个问题解决了没 --------------------编程问答-------------------- setControlEncoding(curCharSet);调用ftp的设置字符集接口 --------------------编程问答-------------------- 解决了没啊?

我也遇到同样的问题! --------------------编程问答--------------------
引用 4 楼  的回复:
楼主问题解决了没有啊?我也是遇到相同的问题了
估计楼主也是用的sun.net.ftp.FtpClient吧 问题解决了的话也告诉我是怎么解决的啊?



4楼 解决了吗? --------------------编程问答-------------------- 设置服务器的编码 与你  本机是一样的,你可以试着用工具传一个,如果你本机工具传上去也是乱码,那就不是你程序的问题 --------------------编程问答-------------------- 首先看看你的服务器FTP是什么编码的,一般window是GBK就可以了,那么你的客户端

ftpClient.setControlEncoding("GBK"); 后也就可以了,如果FTP服务器你设置不了,你可以先发送一个命令给服务器询问支持编码,例如 GBK ON   ,现在不少客户端发送的是UTF8 ON ,服务器收到后会返回信息给你,如果是213表示支持你的编码,就不会有乱码了, 如果你的FTP服务器是自己写的,你就要先检查服务器端的编码设置 --------------------编程问答-------------------- --------------------编程问答-------------------- 楼主,问题解决了吗 ? 我今天也遇到了同样的问题。 --------------------编程问答--------------------
引用 5 楼 xiangyu0921 的回复:
[Quote=引用 4 楼 kkkmoving 的回复:]
楼主问题解决了没有啊?我也是遇到相同的问题了
估计楼主也是用的sun.net.ftp.FtpClient吧 问题解决了的话也告诉我是怎么解决的啊?

就是sun.net.ftp.FtpClient,不过后来改成org.apache.commons.net.ftp.FTPClient,还添加了ftpClient.setControlEncoding("GBK");可惜一样中文文件名就乱码……

我也遇到了这样的问题,下载后的文件名有中文就乱码了,求助啊 --------------------编程问答--------------------
引用 9 楼 yinbing_024 的回复:
setControlEncoding(curCharSet);调用ftp的设置字符集接口

没有用啊,依然乱码。。。 --------------------编程问答-------------------- 除 --------------------编程问答-------------------- package ftpplug;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;

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

public class FtpUtils {

public FTPClient ftp = null;

private String ip = "";

private int port = 21;

private String username = "";

private String password = "";

public FtpUtils() {
ftp = new FTPClient();
}

public boolean uploadFile(String serverpath, String file) {
// 初始表示上传失败  
boolean success = false;
// 创建FTPClient对象 
try {
   //设置PassiveMode传输   
if (!ftp.isConnected()) {
   boolean b=connect();
   if(b==false){
   return success;
   }
}
/* int reply;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}  */
// 转到指定上传目录  
serverpath = gbkToIso8859(serverpath);
if(!checkPathExist(iso8859ToGbk(serverpath))) return false;
if(!ftp.changeWorkingDirectory(iso8859ToGbk(serverpath))){
System.err.print("远程无此目录");
return false;
}

//输入流  
InputStream input = null;
try {
file = gbkToIso8859(file);
input = new FileInputStream(iso8859ToGbk(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 将上传文件存储到指定目录  
file = iso8859ToGbk(file);
if(!ftp.storeFile(iso8859ToGbk(serverpath) +"/"
+ iso8859ToGbk(getFilename(file)), input)){
return false;
}

// 关闭输入流  
input.close();
// 退出ftp  

// 表示上传成功  
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftp.logout();
disconnect();
} catch (IOException ioe) {
}

}
return success;
}

/** 
 * 从FTP服务器下载文件 
 *  
 * @param ip 
 *            FTP服务器ip e.g:192.168.8.22 
 * @param port 
 *            FTP服务器端口 
 * @param username 
 *            FTP登录账号 
 * @param password 
 *            FTP登录密码 
 * @param serverpath 
 *            FTP服务器上的相对路径 默认缺省时指向主目录 
 * @param fileName 
 *            要下载的文件名 
 * @param localPath 
 *            下载后保存到本地的路径 不含文件名 
 * @return 
 *      成功返回true,否则返回false 
 */
public boolean downFile(String serverpath, String fileName, String localPath) { // 初始表示下载失败
boolean success = false;
// 创建FTPClient对象
try {
if (!ftp.isConnected()) {
   boolean b=connect();
   if(b==false){
   return success;
   }
}
/* int reply;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}  */
   
// 转到指定下载目录
serverpath = gbkToIso8859(serverpath);
ftp.changeWorkingDirectory(this.iso8859ToGbk(serverpath));
// 列出该目录下所有文件
FTPFile[] fs = ftp.listFiles();
fileName = this.gbkToIso8859(fileName);
localPath = this.gbkToIso8859(localPath);

// 遍历所有文件,找到指定的文件

for (int i = 0; i < fs.length; i++) {
FTPFile f = fs[i];

if (f.getName().equals(iso8859ToGbk(fileName))) {
// 根据绝对路径初始化文件
File localFile = new File(iso8859ToGbk(localPath) + File.separator
+ f.getName());
File localFileDir = new File(iso8859ToGbk(localPath));
// 保存路径不存在时创建
if (!localFileDir.exists()) {
localFileDir.mkdirs();
}
// 输出流
OutputStream is = new FileOutputStream(localFile);
// 下载文件
ftp.retrieveFile(f.getName(), is);
is.close();
}
}
// 下载成功
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftp.logout();
disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return success;
}

/** 
 *   
 * 查找指定目录是否存在  不存在创建目录 
 *  
 * @param FTPClient  
 *    ftpClient 要检查的FTP服务器 
 * @param String  
 *    filePath 要查找的目录  
 * @return  
 *    boolean:存在:true,不存在:false  
 * @throws IOException  
 */
private boolean checkPathExist(String filePath) throws IOException {
boolean existFlag = false;
try {
if (filePath != null && !filePath.equals("")) {
if (filePath.indexOf("/") != -1) {
int index = 0;
while ((index = filePath.indexOf("/")) != -1) {
if (!ftp.changeWorkingDirectory(filePath.substring(0,
index))) {
ftp.makeDirectory(filePath.substring(0, index));
}
ftp
.changeWorkingDirectory(filePath.substring(0,
index));
filePath = filePath.substring(index + 1, filePath
.length());
}
if (!filePath.equals("")) {
if (!ftp.changeWorkingDirectory(filePath)) {
ftp.makeDirectory(filePath);
}
}
}
existFlag = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return existFlag;
}

/** 
 * 根据绝对路径获得文件名 
 * @param file 
 *      文件绝对路径 e.g: e.g: E:/log/log.txt OR E:\\log\\log.txt 
 * @return 
 *      转码后的文件名  
 */
private String getFilename(String file) {
//文件名  
String filename = "";
if (file != null && !file.equals("")) {
    file = file.replaceAll(Matcher.quoteReplacement("\\"), "/");
String[] strs = file.split("/");
filename = strs[strs.length - 1];
}
filename = gbkToIso8859(filename);//转码  
return filename;
}

/**  
 * 转码[ISO-8859-1 ->  GBK]  
 * 不同的平台需要不同的转码  
 * @param obj  
 * @return  
 */
private String iso8859ToGbk(Object obj) {
try {
if (obj == null)
return "";
else{
String  str= new String(obj.toString().getBytes("iso-8859-1"),"GBK");
return str;

}
} catch (Exception e) {
return "";
}
}

/**  
 * 转码[GBK ->  ISO-8859-1]  
 * 不同的平台需要不同的转码  
 * @param obj  
 * @return  
 */
private String gbkToIso8859(Object obj) {
try {
if (obj == null)
return "";
else
return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
} catch (Exception e) {
return "";
}
}

/** */
/**  
 * 连接到FTP服务器  
 * @param hostname 主机名  
 * @param port 端口  
 * @param username 用户名  
 * @param password 密码  
 * @return 是否连接成功  
 * @throws IOException  
 */
private boolean connect(String hostname, int port, String username,
String password) throws IOException {
ftp.connect(hostname, port);
int reply = ftp.getReplyCode();   
if (FTPReply.isPositiveCompletion(reply)) {
if (ftp.login(username, password)) {
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.setControlEncoding("GBK");
 ftp.enterLocalPassiveMode();
return true;
}
}
disconnect(); 
return false;
}

public boolean connect() throws IOException {
return connect(ip, port, username, password);
}

/** */
/**  
 * 断开与远程服务器的连接  
 * @throws IOException  
 */
public void disconnect() throws IOException {
if (ftp.isConnected()) {
ftp.disconnect();
}
}

public void setFtp(FTPClient ftp) {
this.ftp = ftp;
}

public void setIp(String ip) {
this.ip = ip;
}

public void setPassword(String password) {
this.password = password;
}

public void setPort(int port) {
this.port = port;
}

public void setUsername(String username) {
this.username = username;
}



}
--------------------编程问答-------------------- 先对中文字符编码,然后再解码 --------------------编程问答-------------------- 除 --------------------编程问答-------------------- 必须在connect()方法中setControlEncoding(),否则无效 --------------------编程问答-------------------- 写错,是connect()前。 --------------------编程问答-------------------- 用 import com.enterprisedt.net.ftp.FTPClient; 这个试试呢?
前提也是在connect()前面首先setControlEncoding() --------------------编程问答-------------------- 是不是因为使用IE8的问题?我在用的一个FTP下载软件就有这种问题,IE6下可以正常使用,IE8下中文名的文件就无法下载了. --------------------编程问答-------------------- 是否服务器设置的就有问题呢
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,