Java实现FTP文件与文件夹的上传和下载
FTP是FileTransferProtocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于Internet上的控制文件的双向传输。同时,它也是一个应用程序(Application)。基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件。在FTP的使用当中,用户经常遇到两个概念:"下载"(Download)和"上传"(Upload)。"下载"文件就是从远程主机拷贝文件至自己的计算机上;"上传"文件就是将文件从自己的计算机中拷贝至远程主机上。用Internet语言来说,用户可通过客户机程序向(从)远程主机上传(下载)文件。
首先下载了Serv-U将自己的电脑设置为了FTP文件服务器,方便操作。下面代码的使用都是在FTP服务器已经创建,并且要在代码中写好FTP连接的相关数据才可以完成。
1.FTP文件的上传与下载(注意是单个文件的上传与下载)
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importorg.apache.commons.net.ftp.FTP;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
/**
*实现FTP文件上传和文件下载
*/
publicclassFtpApche{
privatestaticFTPClientftpClient=newFTPClient();
privatestaticStringencoding=System.getProperty("file.encoding");
/**
*Description:向FTP服务器上传文件
*
*@Version1.0
*@paramurl
*FTP服务器hostname
*@paramport
*FTP服务器端口
*@paramusername
*FTP登录账号
*@parampassword
*FTP登录密码
*@parampath
*FTP服务器保存目录,如果是根目录则为“/”
*@paramfilename
*上传到FTP服务器上的文件名
*@paraminput
*本地文件输入流
*@return成功返回true,否则返回false
*/
publicstaticbooleanuploadFile(Stringurl,intport,Stringusername,
Stringpassword,Stringpath,Stringfilename,InputStreaminput){
booleanresult=false;
try{
intreply;
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftpClient.connect(url);
//ftp.connect(url,port);//连接FTP服务器
//登录
ftpClient.login(username,password);
ftpClient.setControlEncoding(encoding);
//检验是否连接成功
reply=ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
System.out.println("连接失败");
ftpClient.disconnect();
returnresult;
}
//转移工作目录至指定目录下
booleanchange=ftpClient.changeWorkingDirectory(path);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if(change){
result=ftpClient.storeFile(newString(filename.getBytes(encoding),"iso-8859-1"),input);
if(result){
System.out.println("上传成功!");
}
}
input.close();
ftpClient.logout();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptionioe){
}
}
}
returnresult;
}
/**
*将本地文件上传到FTP服务器上
*
*/
publicvoidtestUpLoadFromDisk(){
try{
FileInputStreamin=newFileInputStream(newFile("D:/test02/list.txt"));
booleanflag=uploadFile("10.0.0.102",21,"admin","123456","/","lis.txt",in);
System.out.println(flag);
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
}
/**
*Description:从FTP服务器下载文件
*
*@Version1.0
*@paramurl
*FTP服务器hostname
*@paramport
*FTP服务器端口
*@paramusername
*FTP登录账号
*@parampassword
*FTP登录密码
*@paramremotePath
*FTP服务器上的相对路径
*@paramfileName
*要下载的文件名
*@paramlocalPath
*下载后保存到本地的路径
*@return
*/
publicstaticbooleandownFile(Stringurl,intport,Stringusername,
Stringpassword,StringremotePath,StringfileName,
StringlocalPath){
booleanresult=false;
try{
intreply;
ftpClient.setControlEncoding(encoding);
/*
*为了上传和下载中文文件,有些地方建议使用以下两句代替
*newString(remotePath.getBytes(encoding),"iso-8859-1")转码。
*经过测试,通不过。
*/
//FTPClientConfigconf=newFTPClientConfig(FTPClientConfig.SYST_NT);
//conf.setServerLanguageCode("zh");
ftpClient.connect(url,port);
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftpClient.login(username,password);//登录
//设置文件传输类型为二进制
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//获取ftp登录应答代码
reply=ftpClient.getReplyCode();
//验证是否登陆成功
if(!FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
System.err.println("FTPserverrefusedconnection.");
returnresult;
}
//转移到FTP服务器目录至指定的目录下
ftpClient.changeWorkingDirectory(newString(remotePath.getBytes(encoding),"iso-8859-1"));
//获取文件列表
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();
result=true;
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptionioe){
}
}
}
returnresult;
}
/**
*将FTP服务器上文件下载到本地
*
*/
publicvoidtestDownFile(){
try{
booleanflag=downFile("10.0.0.102",21,"admin",
"123456","/","ip.txt","E:/");
System.out.println(flag);
}catch(Exceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
FtpApchefa=newFtpApche();
fa.testDownFile();
fa.testUpLoadFromDisk();
}
}
2.FTP文件夹的上传与下载(注意是整个文件夹)
packageftp;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.util.TimeZone;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPClientConfig;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importorg.apache.log4j.Logger;
publicclassFTPTest_04{
privateFTPClientftpClient;
privateStringstrIp;
privateintintPort;
privateStringuser;
privateStringpassword;
privatestaticLoggerlogger=Logger.getLogger(FTPTest_04.class.getName());
/**
*Ftp构造函数
*/
publicFTPTest_04(StringstrIp,intintPort,Stringuser,StringPassword){
this.strIp=strIp;
this.intPort=intPort;
this.user=user;
this.password=Password;
this.ftpClient=newFTPClient();
}
/**
*@return判断是否登入成功
**/
publicbooleanftpLogin(){
booleanisLogin=false;
FTPClientConfigftpClientConfig=newFTPClientConfig();
ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
this.ftpClient.setControlEncoding("GBK");
this.ftpClient.configure(ftpClientConfig);
try{
if(this.intPort>0){
this.ftpClient.connect(this.strIp,this.intPort);
}else{
this.ftpClient.connect(this.strIp);
}
//FTP服务器连接回答
intreply=this.ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
this.ftpClient.disconnect();
logger.error("登录FTP服务失败!");
returnisLogin;
}
this.ftpClient.login(this.user,this.password);
//设置传输协议
this.ftpClient.enterLocalPassiveMode();
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
logger.info("恭喜"+this.user+"成功登陆FTP服务器");
isLogin=true;
}catch(Exceptione){
e.printStackTrace();
logger.error(this.user+"登录FTP服务失败!"+e.getMessage());
}
this.ftpClient.setBufferSize(1024*2);
this.ftpClient.setDataTimeout(30*1000);
returnisLogin;
}
/**
*@退出关闭服务器链接
**/
publicvoidftpLogOut(){
if(null!=this.ftpClient&&this.ftpClient.isConnected()){
try{
booleanreuslt=this.ftpClient.logout();//退出FTP服务器
if(reuslt){
logger.info("成功退出服务器");
}
}catch(IOExceptione){
e.printStackTrace();
logger.warn("退出FTP服务器异常!"+e.getMessage());
}finally{
try{
this.ftpClient.disconnect();//关闭FTP服务器的连接
}catch(IOExceptione){
e.printStackTrace();
logger.warn("关闭FTP服务器的连接异常!");
}
}
}
}
/***
*上传Ftp文件
*@paramlocalFile当地文件
*@paramromotUpLoadePath上传服务器路径-应该以/结束
**/
publicbooleanuploadFile(FilelocalFile,StringromotUpLoadePath){
BufferedInputStreaminStream=null;
booleansuccess=false;
try{
this.ftpClient.changeWorkingDirectory(romotUpLoadePath);//改变工作路径
inStream=newBufferedInputStream(newFileInputStream(localFile));
logger.info(localFile.getName()+"开始上传.....");
success=this.ftpClient.storeFile(localFile.getName(),inStream);
if(success==true){
logger.info(localFile.getName()+"上传成功");
returnsuccess;
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
logger.error(localFile+"未找到");
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(inStream!=null){
try{
inStream.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnsuccess;
}
/***
*下载文件
*@paramremoteFileName待下载文件名称
*@paramlocalDires下载到当地那个路径下
*@paramremoteDownLoadPathremoteFileName所在的路径
**/
publicbooleandownloadFile(StringremoteFileName,StringlocalDires,
StringremoteDownLoadPath){
StringstrFilePath=localDires+remoteFileName;
BufferedOutputStreamoutStream=null;
booleansuccess=false;
try{
this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream=newBufferedOutputStream(newFileOutputStream(
strFilePath));
logger.info(remoteFileName+"开始下载....");
success=this.ftpClient.retrieveFile(remoteFileName,outStream);
if(success==true){
logger.info(remoteFileName+"成功下载到"+strFilePath);
returnsuccess;
}
}catch(Exceptione){
e.printStackTrace();
logger.error(remoteFileName+"下载失败");
}finally{
if(null!=outStream){
try{
outStream.flush();
outStream.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
if(success==false){
logger.error(remoteFileName+"下载失败!!!");
}
returnsuccess;
}
/***
*@上传文件夹
*@paramlocalDirectory
*当地文件夹
*@paramremoteDirectoryPath
*Ftp服务器路径以目录"/"结束
**/
publicbooleanuploadDirectory(StringlocalDirectory,
StringremoteDirectoryPath){
Filesrc=newFile(localDirectory);
try{
remoteDirectoryPath=remoteDirectoryPath+src.getName()+"/";
booleanmakeDirFlag=this.ftpClient.makeDirectory(remoteDirectoryPath);
System.out.println("localDirectory:"+localDirectory);
System.out.println("remoteDirectoryPath:"+remoteDirectoryPath);
System.out.println("src.getName():"+src.getName());
System.out.println("remoteDirectoryPath:"+remoteDirectoryPath);
System.out.println("makeDirFlag:"+makeDirFlag);
//ftpClient.listDirectories();
}catch(IOExceptione){
e.printStackTrace();
logger.info(remoteDirectoryPath+"目录创建失败");
}
File[]allFile=src.listFiles();
for(intcurrentFile=0;currentFile<allFile.length;currentFile++){
if(!allFile[currentFile].isDirectory()){
StringsrcName=allFile[currentFile].getPath().toString();
uploadFile(newFile(srcName),remoteDirectoryPath);
}
}
for(intcurrentFile=0;currentFile<allFile.length;currentFile++){
if(allFile[currentFile].isDirectory()){
//递归
uploadDirectory(allFile[currentFile].getPath().toString(),
remoteDirectoryPath);
}
}
returntrue;
}
/***
*@下载文件夹
*@paramlocalDirectoryPath本地地址
*@paramremoteDirectory远程文件夹
**/
publicbooleandownLoadDirectory(StringlocalDirectoryPath,StringremoteDirectory){
try{
StringfileName=newFile(remoteDirectory).getName();
localDirectoryPath=localDirectoryPath+fileName+"//";
newFile(localDirectoryPath).mkdirs();
FTPFile[]allFile=this.ftpClient.listFiles(remoteDirectory);
for(intcurrentFile=0;currentFile<allFile.length;currentFile++){
if(!allFile[currentFile].isDirectory()){
downloadFile(allFile[currentFile].getName(),localDirectoryPath,remoteDirectory);
}
}
for(intcurrentFile=0;currentFile<allFile.length;currentFile++){
if(allFile[currentFile].isDirectory()){
StringstrremoteDirectoryPath=remoteDirectory+"/"+allFile[currentFile].getName();
downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
}
}
}catch(IOExceptione){
e.printStackTrace();
logger.info("下载文件夹失败");
returnfalse;
}
returntrue;
}
//FtpClient的Set和Get函数
publicFTPClientgetFtpClient(){
returnftpClient;
}
publicvoidsetFtpClient(FTPClientftpClient){
this.ftpClient=ftpClient;
}
publicstaticvoidmain(String[]args)throwsIOException{
FTPTest_04ftp=newFTPTest_04("10.0.0.102",21,"admin","123456");
ftp.ftpLogin();
System.out.println("1");
//上传文件夹
booleanuploadFlag=ftp.uploadDirectory("D:\\test02","/");//如果是admin/那么传的就是所有文件,如果只是/那么就是传文件夹
System.out.println("uploadFlag:"+uploadFlag);
//下载文件夹
ftp.downLoadDirectory("d:\\tm","/");
ftp.ftpLogOut();
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!