java使用Apache工具集实现ftp文件传输代码详解
本文主要介绍如何使用Apache工具集commons-net提供的ftp工具实现向ftp服务器上传和下载文件。
一、准备
需要引用commons-net-3.5.jar包。
使用maven导入:
commons-net commons-net 3.5
手动下载:
https://www.nhooo.com/softs/550085.html
二、连接FTPServer
/**
*连接FTPServer
*@throwsIOException
*/
publicstaticfinalStringANONYMOUS_USER="anonymous";
privateFTPClientconnect(){
FTPClientclient=newFTPClient();
try{
//连接FTPServer
client.connect(this.host,this.port);
//登陆
if(this.user==null||"".equals(this.user)){
//使用匿名登陆
client.login(ANONYMOUS_USER,ANONYMOUS_USER);
}else{
client.login(this.user,this.password);
}
//设置文件格式
client.setFileType(FTPClient.BINARY_FILE_TYPE);
//获取FTPServer应答
intreply=client.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
client.disconnect();
returnnull;
}
//切换工作目录
changeWorkingDirectory(client);
System.out.println("===连接到FTP:"+host+":"+port);
}
catch(IOExceptione){
returnnull;
}
returnclient;
}
/**
*切换工作目录,远程目录不存在时,创建目录
*@paramclient
*@throwsIOException
*/
privatevoidchangeWorkingDirectory(FTPClientclient)throwsIOException{
if(this.ftpPath!=null&&!"".equals(this.ftpPath)){
Booleanok=client.changeWorkingDirectory(this.ftpPath);
if(!ok){
//ftpPath不存在,手动创建目录
StringTokenizertoken=newStringTokenizer(this.ftpPath,"\\//");
while(token.hasMoreTokens()){
Stringpath=token.nextToken();
client.makeDirectory(path);
client.changeWorkingDirectory(path);
}
}
}
}
/**
*断开FTP连接
*@paramftpClient
*@throwsIOException
*/
publicvoidclose(FTPClientftpClient)throwsIOException{
if(ftpClient!=null&&ftpClient.isConnected()){
ftpClient.logout();
ftpClient.disconnect();
}
System.out.println("!!!断开FTP连接:"+host+":"+port);
}
host:ftp服务器ip地址
port:ftp服务器端口
user:登陆用户
password:登陆密码
登陆用户为空时,使用匿名用户登陆。
ftpPath:ftp路径,ftp路径不存在时自动创建,如果是多层目录结构,需要迭代创建目录。
三、上传文件
/**
*上传文件
*@paramtargetName上传到ftp文件名
*@paramlocalFile本地文件路径
*@return
*/
publicBooleanupload(StringtargetName,StringlocalFile){
//连接ftpserver
FTPClientftpClient=connect();
if(ftpClient==null){
System.out.println("连接FTP服务器["+host+":"+port+"]失败!");
returnfalse;
}
Filefile=newFile(localFile);
//设置上传后文件名
if(targetName==null||"".equals(targetName))
targetName=file.getName();
FileInputStreamfis=null;
try{
longnow=System.currentTimeMillis();
//开始上传文件
fis=newFileInputStream(file);
System.out.println(">>>开始上传文件:"+file.getName());
Booleanok=ftpClient.storeFile(targetName,fis);
if(ok){
//上传成功
longtimes=System.currentTimeMillis()-now;
System.out.println(String.format(">>>上传成功:大小:%s,上传时间:%d秒",formatSize(file.length()),times/1000));
}else//上传失败
System.out.println(String.format(">>>上传失败:大小:%s",formatSize(file.length())));
}
catch(IOExceptione){
System.err.println(String.format(">>>上传失败:大小:%s",formatSize(file.length())));
e.printStackTrace();
returnfalse;
}
finally{
try{
if(fis!=null)
fis.close();
close(ftpClient);
}
catch(Exceptione){
}
}
returntrue;
}
四、下载文件
/**
*下载文件
*@paramlocalPath本地存放路径
*@return
*/
publicintdownload(StringlocalPath){
//连接ftpserver
FTPClientftpClient=connect();
if(ftpClient==null){
System.out.println("连接FTP服务器["+host+":"+port+"]失败!");
return0;
}
Filedir=newFile(localPath);
if(!dir.exists())
dir.mkdirs();
FTPFile[]ftpFiles=null;
try{
ftpFiles=ftpClient.listFiles();
if(ftpFiles==null||ftpFiles.length==0)
return0;
}
catch(IOExceptione){
return0;
}
intc=0;
for(inti=0;i
格式化文件大小
privatestaticfinalDecimalFormatDF=newDecimalFormat("#.##");
/**
*格式化文件大小(B,KB,MB,GB)
*@paramsize
*@return
*/
privateStringformatSize(longsize){
if(size<1024){
returnsize+"B";
}elseif(size<1024*1024){
returnsize/1024+"KB";
}elseif(size<1024*1024*1024){
return(size/(1024*1024))+"MB";
}else{
doublegb=size/(1024*1024*1024);
returnDF.format(gb)+"GB";
}
}
五、测试
publicstaticvoidmain(Stringargs[]){
FTPTestftp=newFTPTest("192.168.1.10",21,null,null,"/temp/2016/12");
ftp.upload("newFile.rar","D:/ftp/TeamViewerPortable.rar");
System.out.println("");
ftp.download("D:/ftp/");
}
结果
===连接到FTP:192.168.1.10:21
>>>开始上传文件:TeamViewerPortable.rar
>>>上传成功:大小:5MB,上传时间:3秒
!!!断开FTP连接:192.168.1.10:21
===连接到FTP:192.168.1.10:21
<<<开始下载文件:newFile.rar
<<<下载成功:大小:5MB,上传时间:4秒
!!!断开FTP连接:192.168.1.10:21
总结
以上就是本文关于java使用Apache工具集实现ftp文件传输代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。