FTPClient 删除中文文件夹下的文件

syeia 2012-10-16 09:05:43
FTPClient 删除中文文件夹下的文件,如果中文文件夹在程序中写死,通过转换可以删除,如下:
String remoteDir="/aa/测试";
remoteDir=new String(remoteDir.getBytes(“UTF-8”), "iso-8859-1");
FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir); //得到ftp下 /aa/测试/下的文件。

但如果是文件夹从数据库读出的。则删除了。

String remoteDir="/aa/"+sFolder; //sFolder="测试";
remoteDir=new String(remoteDir.getBytes(“UTF-8”), "iso-8859-1");
FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir); //也能遍历文件夹下的文件就是删除不了,原因是中文文件夹变成 ???(乱码)

请问该如何 转换?

先谢过了。

...全文
1019 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
dblhd 2015-04-20
  • 打赏
  • 举报
回复
这个问题楼主解决没?同遇,求解答
紅塵 2014-05-07
  • 打赏
  • 举报
回复
/**
	 * 删除文件或文件夹
	 * 
	 * @param path
	 *            待删除文件的绝对路径
	 * @return boolean
	 */
	public boolean deleteFile(String path) throws ServiceException {

		if (ftpClient != null) {
			try {
				
				//如果是文件直接删除
				ftpClient.deleteFile(path);

				if (ftpClient.changeWorkingDirectory(path)) {
					//是文件夹
					FTPFile[] ftpFiles = ftpClient.listFiles();
					if (ftpFiles == null || ftpFiles.length <= 0) {
						
						//文件夹文空直接删除
						ftpClient.removeDirectory(path);
						return true;
					}
					for (FTPFile ftpFile : ftpFiles) {
						//文件夹不为空,先删文件再删文件夹
						ftpClient.deleteFile(path+"/"+ftpFile.getName());
    					ftpClient.removeDirectory(path);
					}
				}
			} catch (IOException e) {
				throw new ServiceException(e.getMessage(), e);
			}
		}
		return true;
	}
liangyl 2012-10-23
  • 打赏
  • 举报
回复
终于解决了!如下,
在listFile函数中加入ftp.setControlEncoding("UTF-8");即可。
呵呵。
无论是写死,还是动态调用都可以了。
哎呀,网上搜了一大堆,每个人的问题都不一样,实在不懂那么多编码为毛。
liangyl 2012-10-23
  • 打赏
  • 举报
回复
遇到和楼主一模一样的问题。
怀疑listFile函数的问题,我试了下,那个结果用utf-8,iso-8859-1 gbk,均不能得到正确结果,不知打那个编码到底是什么,也许根本不是编码的问题
zhanghua4109 2012-10-19
  • 打赏
  • 举报
回复
package nc.ui.doc.doc_007;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import nc.itf.doc.DocDelegator;
import nc.vo.doc.doc_007.DirVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;

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


public class FtpTool {


private FTPClient ftp;

private String romateDir = "";

private String userName = "";

private String password = "";

private String host = "";

private String port = "21";

public FtpTool(String url) throws IOException {
//String url="ftp://user:password@ip:port/ftptest/psd";
int len = url.indexOf("//");
String strTemp = url.substring(len + 2);
len = strTemp.indexOf(":");
userName = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);

len = strTemp.indexOf("@");
password = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
host = "";
len = strTemp.indexOf(":");
if (len < 0)//没有设置端口
{
port = "21";
len = strTemp.indexOf("/");
if (len > -1) {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
strTemp = "";
}
} else {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
len = strTemp.indexOf("/");
if (len > -1) {
port = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
port = "21";
strTemp = "";
}
}
romateDir = strTemp;
ftp = new FTPClient();
ftp.connect(host, FormatStringToInt(port));

}

public FtpTool(String host, int port) throws IOException {
ftp = new FTPClient();
ftp.connect(host, port);
}

public String login(String username, String password) throws IOException {
this.ftp.login(username, password);
return this.ftp.getReplyString();
}

public String login() throws IOException {
this.ftp.login(userName, password);
System.out.println("ftp用户: " + userName);
System.out.println("ftp密码: " + password);
if (!romateDir.equals(""))
System.out.println("cd " + romateDir);
ftp.changeWorkingDirectory(romateDir);
return this.ftp.getReplyString();
}

public boolean upload(String pathname, String filename) throws IOException, BusinessException {

int reply;
int j;
String m_sfilename = null;
filename = CheckNullString(filename);
if (filename.equals(""))
return false;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("FTP server refused connection.");
System.exit(1);
}
FileInputStream is = null;
try {
File file_in;
if (pathname.endsWith(File.separator)) {
file_in = new File(pathname + filename);
} else {
file_in = new File(pathname + File.separator + filename);
}
if (file_in.length() == 0) {
System.out.println("上传文件为空!");
return false;
}
//产生随机数最大到99
j = (int)(Math.random()*100);
m_sfilename = String.valueOf(j) + ".pdf"; // 生成的文件名
is = new FileInputStream(file_in);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.storeFile(m_sfilename, is);
ftp.logout();


} finally {
if (is != null) {
is.close();
}
}
System.out.println("上传文件成功!");
return true;
}


public boolean delete(String filename) throws IOException {

FileInputStream is = null;
boolean retValue = false;
try {
retValue = ftp.deleteFile(filename);
ftp.logout();
} finally {
if (is != null) {
is.close();
}
}
return retValue;

}

public void close() {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static int FormatStringToInt(String p_String) {
int intRe = 0;
if (p_String != null) {
if (!p_String.trim().equals("")) {
try {
intRe = Integer.parseInt(p_String);
} catch (Exception ex) {

}
}
}
return intRe;
}

public static String CheckNullString(String p_String) {
if (p_String == null)
return "";
else
return p_String;
}

public boolean downfile(String pathname, String filename) {

String outputFileName = null;
boolean retValue = false;
try {
FTPFile files[] = ftp.listFiles();
int reply = ftp.getReplyCode();

////////////////////////////////////////////////
if (!FTPReply.isPositiveCompletion(reply)) {
try {
throw new Exception("Unable to get list of files to dowload.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/////////////////////////////////////////////////////
if (files.length == 0) {
System.out.println("No files are available for download.");
}else {
for (int i=0; i <files.length; i++) {
System.out.println("Downloading file "+files[i].getName()+"Size:"+files[i].getSize());
outputFileName = pathname + filename + ".pdf";
//return outputFileName;
File f = new File(outputFileName);

//////////////////////////////////////////////////////
retValue = ftp.retrieveFile(outputFileName, new FileOutputStream(f));

if (!retValue) {
try {
throw new Exception ("Downloading of remote file"+files[i].getName()+" failed. ftp.retrieveFile() returned false.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

/////////////////////////////////////////////////////////////
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retValue;
}

}
试试这个
哎呦喂哈 2012-10-19
  • 打赏
  • 举报
回复
先弱弱的问下new String(remoteDir.getBytes(“UTF-8”), "iso-8859-1");是将UTF-8转换为ISO-8859-1吗?
如果是的话,个人观点:从程序中直接写汉字可以转而从数据库中取出来不可以转,说明从程序中直接写汉字,编码为UTF-8,而数据库中取出来的则不是UTF-8,所以会变乱码。
反之new String(remoteDir.getBytes(“UTF-8”), "iso-8859-1");是将iso-8859-1转为UTF-8也一样。
个人观点而已,没有测试。
syeia 2012-10-17
  • 打赏
  • 举报
回复
从数据库中读出的文件夹名称不是乱码,能正常显示,就是 传入
FTPFile[] remoteFiles = ftpClient.listFiles(remoteDir);
中,就不能得到该文件夹下的文件。必须通过转码,但如果是从程序中直接写的中文按照
remoteDir=new String(remoteDir.getBytes(“UTF-8”), "iso-8859-1");
转码就可以了,但从数据库中读取出来的,按照这个转,能得到该文件夹下的文件个数,
就是不能正常对该文件夹下的文件进行操作,从调试看得出的文件夹 是 ???? 乱码,因此不知道该如何转码。
syeia 2012-10-16
  • 打赏
  • 举报
回复
上述加了,不行。
有没有谁遇到过?
wula0010 2012-10-16
  • 打赏
  • 举报
回复

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


增加这个设置试试............
yjbren 2012-10-16
  • 打赏
  • 举报
回复
我说下自己的拙见啊,你说从数据库中拿出文件夹,是说的是文件夹的路径吗?那可能是从数据库中拿出来的时候就是乱码吗?如果是的话,看看在URL后边加上相应的字符格式代码试试啊,如果不是的话再看别人怎么说吧,没有测试,只是想法
syeia 2012-10-16
  • 打赏
  • 举报
回复
悲伤,就这样沉下去了,不甘心。。。
public class FTPUtil { private FTPClient ftpClient=null; private boolean result = false; private FileInputStream fis; String ftpHost = "10.16.111.111"; String port = 21 String ftpUserName = "ftpuser11; String ftpPassword = "1234561"; /** * 登录服务器 * @param ftpInfo * @return * @throws IOException */ public FTPClient login() throws IOException { ftpClient = new FTPClient(); ftpClient.connect(ftpHost); boolean login = ftpClient.login(ftpUserName,ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } if(login){ System.out.println("ftp连接成功!"); }else{ System.out.println("ftp连接失败!"); } //ftpClient.setControlEncoding("GBK"); return ftpClient; } /** * 字符串作为文件上传指定目录 下 * @param content 源字符串 * @param uploadDir 上传目录 * @param ftpFileName 上传文件名称 * @throws Exception */ public void ftpUploadByText(String content ,String uploadDir,String ftpFileName) throws Exception{ try { ftpClient = this.login(); //创建目录 createDir(ftpClient,uploadDir); // 设置上传目录 这个也应该用配置文件读取 ftpClient.changeWorkingDirectory(uploadDir); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); String fileName = new String(ftpFileName.getBytes("GBK"),"iso-8859-1"); OutputStream os = ftpClient.storeFileStream(fileName); byte[] bytes = content.getBytes(); os.write(bytes); os.flush(); os.close(); } catch (Exception e) { ftpClient.disconnect(); ftpClient = null; e.printStackTrace(); throw e; }finally{ ftpClient.disconnect(); ftpClient = null; } } /** * 移动文件 * @param ftpInfo * @return * @throws Exception */ public boolean moveFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.moveFile(ftpClient, ftpInfo.getChangeWorkingDirectoryPath(), ftpInfo.getFilePath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 删除文件 * @param ftpInfo * @return * @throws Exception */ public boolean deleteFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.deleteByFolder(ftpClient, ftpInfo.getChangeWorkingDirectoryPath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 实现文件的移动,这里做的是一个文件下的所有内容移动到新的文件, * 如果要做指定文件移动,加个判断判断文件名 * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName) * @param ftp * @param oldPath * @param newPath * @return */ public boolean moveFile(FTPClient ftp,String oldPath,String newPath){ boolean flag = false; try { ftp.changeWorkingDirectory(oldPath); ftp.enterLocalPassiveMode(); //获取文件数组 FTPFile[] files = ftp.listFiles(); //新文件不存在则创建 if(!ftp.changeWorkingDirectory(newPath)){ ftp.makeDirectory(newPath); } //回到原有工作目录 ftp.changeWorkingDirectory(oldPath); for (FTPFile file : files) { if(file.isDirectory()) { moveFile(ftp,oldPath+file.getName()+"/" ,newPath+file.getName()+"/"); }else{ //转存目录 flag = ftp.rename(oldPath+new String(file.getName().getBytes("GBK"),"ISO-8859-1"), newPath+"/"+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } if(flag){ System.out.println(file.getName()+"移动成功"); }else{ System.out.println(file.getName()+"移动失败"); } } ftp.removeDirectory(new String(oldPath.getBytes("GBK"),"ISO-8859-1")); } catch (Exception e) { e.printStackTrace(); System.out.println("移动文件失败"); } return flag; } /** * 删除FTP上指定文件文件及其子文件方法,添加了对中文目录的支持 * @param ftp FTPClient对象 * @param FtpFolder 需要删除文件 * @return */ public boolean deleteByFolder(FTPClient ftp,String FtpFolder){ boolean flag = false; try { ftp.changeWorkingDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); ftp.enterLocalPassiveMode(); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { //判断为文件删除 if(file.isFile()){ ftp.deleteFile(FtpFolder+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } //判断是文件 if(file.isDirectory()){ String childPath = FtpFolder +file.getName()+ "/"; //递归删除文件 deleteByFolder(ftp,childPath); } } //循环完成后删除文件 flag = ftp.removeDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); if(flag){ System.out.println(FtpFolder+"文件删除成功"); }else{ System.out.println(FtpFolder+"文件删除成功"); } } catch (Exception e) { e.printStackTrace(); System.out.println("删除失败"); } return flag; } /** * 创建目录 * @param createpath * @param sftp */ public void createDir(FTPClient ftpClient,String createpath) throws Exception { try { if(ftpClient.changeWorkingDirectory(createpath)) { return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if(!ftpClient.changeWorkingDirectory(filePath.toString())) { ftpClient.makeDirectory(filePath.toString()); ftpClient.changeWorkingDirectory(filePath.toString()); } } ftpClient.changeWorkingDirectory(createpath); }catch (Exception e) { e.printStackTrace(); throw new Exception("创建路径错误:" + createpath); } } }

67,516

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧