日期:2014-05-17 浏览次数:21069 次
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;
}
//判斷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")){//L