public static boolean downloadFile(String ip, int port, String username,
String password, String remotePath, String fileName,
String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ip, port);
// 下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
conf.setServerLanguageCode("zh");
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
System.out.println("reply:"+reply);
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (int i = 0; i < fs.length; i++) {
FTPFile ff = fs[i];
if (!ff.getName().equals(".") && !ff.getName().equals("..")) { File localFile = new File(localPath + File.separator
+ ff.getName());
if(!localFile.exists())//如果文件已存在则不重复下载
{
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();
}
}
} SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ftp.logout();
success = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}
return success;
}
downloadFile("132.228.39.77", 21, "oa_user", "oa_user","/attachments", "", "");上面这段代码在我本地运行木有问题,可以获取到文件列表;但是放到服务器(Linux)上运行获取不到文件列表
请高手帮忙看看!
谢谢!
看了看你的编程风格,问题可能出在: File.separatorWindows下你用File.separator 得到的是 \
但在Linux下你用用File.separator 得到的是 /但你所访问的FTP服务器,可能只认识 \
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
你先用System.out.println(remotePath); 看看输出的内容,是否跟Windows下的不一致?
//判斷os是windows還是linux
Properties prop = System.getProperties();
String os = prop.getProperty("os.name");
if(os.toLowerCase().indexOf("windows") != -1){//windows
filePath= localPath + "\\"
+ ff.getName();
}else if(os.toLowerCase().equals("linux")){//Linux
filePath= localPath + "/"
+ ff.getName();
}