JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件,本文简单介绍如何利用jakartacommons中的FTPClient(在commons-net包中)实现上传下载文件,我创建的是mvn项目,所以在pom.xml文件中添加依赖:
自己写代码前可以先看下官方的API,官网写的还是很详细的(http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html),简单截个图看下:
好了,简单写个例子,很简单,一看就明白了
/**
*向FTP服务器上传文件
*
*@paramurlFTP服务器url
*@paramportFTP服务器端口
*@paramusername
*@parampassword
*@parampath本地文件目录
*@paramremoteFileFTP服务器保存文件名
*/
publicvoidsendToServer(Stringurl,intport,Stringusername,Stringpassword,
Stringpath,StringremoteFile){
//创建ftp客户端
FTPClientftpClient=newFTPClient();
ftpClient.setControlEncoding("GBK");
try{
//链接ftp服务器
ftpClient.connect(url,port);
//登录ftp
ftpClient.login(username,password);
intreply=ftpClient.getReplyCode();
System.out.println(reply);
//如果reply返回230就算成功了,如果返回530密码用户名错误或当前用户无权限下面有详细的解释。
if(!FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
return;
}
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.changeWorkingDirectory("/data");//修改工作目录
Filefile=newFile(path);
InputStreaminput=newFileInputStream(file);
ftpClient.storeFile(remoteFile,input);//文件名若是不指定就会上传到root目录下
input.close();
ftpClient.logout();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptionioe){
ioe.printStackTrace();
}
}
}
}
/**
*Description:从FTP服务器下载文件
*
*@paramremotePathFTP服务器上的相对路径
*@paramfileName要下载的文件名
*@paramlocalPath下载后保存到本地的路径
*/
publicstaticbooleandownload(Stringurl,intport,Stringusername,Stringpassword,
StringremotePath,StringfileName,StringlocalPath){
booleansuccess=false;
//创建ftp客户端
FTPClientftpClient=newFTPClient();
ftpClient.setControlEncoding("GBK");
try{
intreply;
ftpClient.connect(url,port);
//如果采用默认端口,可以使用ftpClient.connect(url)的方式直接连接FTP服务器
ftpClient.login(username,password);//登录
reply=ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
returnfalse;
}
ftpClient.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
FTPFile[]fs=ftpClient.listFiles();
for(FTPFileff:fs){
if(ff.getName().equals(fileName)){
FilelocalFile=newFile(localPath+"/"+ff.getName());
OutputStreamis=newFileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName(),is);
is.close();
}
}
ftpClient.logout();
success=true;
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptionioe){
}
}
}
returnsuccess;
}
原文链接:https://blog.csdn.net/xuemengrui12/article/details/78183170