FTP上传时怎么解决中文路径和中文名称

如题所述

第1个回答  推荐于2016-07-01
java上传文件到ftp有两种实现方式,一种是使用sun公司提供的sun.net.ftp包里面的FtpClient,另一种是Apache组织提供的org.apache.commons.net.ftp包里的FTPClient,现在我来分别说下两种实现方式。
sun的FtpClient:我们先来看如下代码
public static boolean uploadFileBySun(StringBuffer fileContent,String server,String userName, String userPassword, String path, String fileName) {
FtpClient ftpClient = new FtpClient();
try {
//打开ftp服务器
ftpClient.openServer(server);
//使用指定用户登录
ftpClient.login(userName, userPassword);
//转到指定路径
ftpClient.cd(path);
TelnetOutputStream os = null;
//新建一个文件
// os = ftpClient.put(new String(fileName.getBytes("GBK"), "iso-8859-1"));
os = ftpClient.put(fileName);
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(fileContent.toString());
bw.flush();
bw.close();
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
} finally {
try {
//关闭ftp连接
ftpClient.closeServer();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}

代码结束符!
正如上面的代码,上传文件分为六步,第一步,打开ftp服务器,第二步,使用指定用户名以及密码登陆,第三步,转到指定文件路径,第四步,创建一个文件,第五步,往文件里面写东西,并关闭文件,第六步,释放ftp连接。最后一步释放ftp连接很重要,一般ftp服务器连接数都是有限的,所以不管文件上传成功或是失败都必须释放连接。上面这个例子上传的文件是字符串文本,必须要提的是,如果上传的字符串文本较长(我项目中上传的文本大概在160kb上下),使用上面的方法可能会出现字符串丢失的情况,原因不明,可能跟缓存有关,所以如果文本较长,建议用户使用字节流。还有一个问题,如果要上传的文件名是中文的话,上传的文件名将是乱码,乱码问题我尝试许多转码也解决不了,于是不得不使用下面的方法了。
Apache的FTPClient:
public static boolean uploadFileByApacheByBinary(StringBuffer fileContent,String server,String userName, String userPassword, String path, String fileName) {
FTPClient ftpClient = new FTPClient();
try {
InputStream is = null;
is = new ByteArrayInputStream(fileContent.toString().getBytes());
ftpClient.connect(server);
ftpClient.login(userName, userPassword);
ftpClient.changeWorkingDirectory(path);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(new String(fileName.getBytes("GBK"), "iso-8859-1") , is);
is.close();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if(ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return true;
}

代码结束符!
Apache上传文件的步骤跟sun的实现基本一致,只是方法名有些区别而已。在这里我将字符串文本转换成了ByteArrayInputStream字节缓冲流,这是个很有用的东西,常用来进行字符到流的转换。转换成字节上传就不会出现丢失文件内容的情况了。ftpClient.storeFile(new String(fileName.getBytes(“GBK”), “iso-8859-1″) , is)这句代码将is输入流的东西上传到ftp服务器的fileName文件中,在这里我们对fileName文件名进行了转码,经测试中文没有乱码(ftp服务器使用的是window,其他平台未测试),而如果我们使用sun的ftp实现,即使文件名进行这样类似的转码,依然是乱码。本回答被提问者和网友采纳
相似回答