版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhong_jay/article/details/78934218
1.FTP服务是filezilla server。
下载地址:
https://filezilla-project.org/
2.filezilla server安装及配置教程
教程地址:
https://jingyan.baidu.com/article/17bd8e521067fe85ab2bb8ee.html
3.依赖jar包:commons-net-3.1,httpclient-4.3.5,httpcore-4.4.5
下载地址:
http://download.csdn.net/download/zhong_jay/10180699
4.代码如下:
/**
*
* @Title: ftpDownload
* @Description: ftp跨服务器文件获取
* @author jay
* @date 2017年12月29日 下午7:05:13
* @return boolean
*
* @param ftpUrl ftp服务地址
* @param userName //登录名
* @param pass //密码
* @param port //端口号,默认21
* @param directory //FTP服务器上的相对路径 ,\\代表根目录
* @param fileName //要获取的文件名
* @param localPath //获取后保存到本地的路径
* @return
* @throws IOException
*/
public static boolean ftpDownload(String ftpUrl,String userName,String pass,int port,String directory,
String fileName,String localPath) throws IOException{
FTPClient ftpClient = new FTPClient();
int reply;
try {
ftpClient.connect(ftpUrl,port);
ftpClient.login(userName, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.changeWorkingDirectory(directory);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//设置连接超时和数据传输超时,对于性能有要求的项目,设置这两个属性很重要。例如,设置为60秒:
ftpClient.setDataTimeout(60000); //设置传输超时时间为60秒
ftpClient.setConnectTimeout(60000); //连接超时为60秒
reply = ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)) { //reply状态标识码,200<=reply<300登录成功
ftpClient.disconnect();
System.err.println("FTP服务连接失败,请检查相关参数是否正确!");
System.exit(1);
return false;
}
//获取FTP对应路径下的文件集合
FTPFile[] fs = ftpClient.listFiles();
for(FTPFile ff:fs){ //下载当前目录下所有文件
if(ff.getName().equals(fileName)){
String path=localPath+"\\"+ff.getName();
File localFile = new File(path);
OutputStream is = new FileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName(), is);
is.close();
}
}
System.out.println("FTP文件下载成功!");
return true;
} catch(NumberFormatException e){
throw e;
} catch(FileNotFoundException e){
throw new FileNotFoundException();
} catch (IOException e) {
throw new IOException(e);
} finally {
if(ftpClient.isConnected()){
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
}