利用Apache commons net 包实现FTP上传和下载
2014-12-25 11:54
519 查看
在使用这个方法之前,要做一些准备工作。首先要有一个能用的FTP服务,并且有能够上传下载的账户。
不同的操作系统可能会有一些路径上的差异,需要注意。
下面的代码包括 FTP登陆,上传文件,上传文件夹,下载,退出登陆 五个功能模块。
package test.ffm83.commons.net.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* 通过commons net中的FTP包进行FTP的简单操作.FTP登陆,上传文件,上传文件夹,下载,退出登陆
* @author范芳铭
*/
public
classEasyFTPClientUsage {
private FTPClient
ftpClient;
private String
strIp;
private
int intPort;
private String
user;
private String
password;
/* *
* Ftp构造函数
*/
publicEasyFTPClientUsage(String strIp,
int intPort, String user,
StringPassword) {
this.strIp = strIp;
this.intPort = intPort;
this.user = user;
this.password = Password;
this.ftpClient =
new FTPClient();
}
/**
* @return判断是否登入成功
* */
public
boolean ftpLogin() {
boolean isLogin =
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服务器连接回答
int reply =
this.ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)){
this.ftpClient.disconnect();
System.out.println("登录FTP服务失败!");
return isLogin;
}
this.ftpClient.login(this.user,
this.password);
// 设置传输协议
this.ftpClient.enterLocalPassiveMode();
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
System.out.println("恭喜" +
this.user +
"成功登陆FTP服务器:" +
this.strIp );
isLogin= true;
}catch(Exception e) {
e.printStackTrace();
System.out.println(this.user +
"登录FTP服务失败!" + e.getMessage());
}
this.ftpClient.setBufferSize(1024 *2);
this.ftpClient.setDataTimeout(30 *1000);
return isLogin;
}
/**
* @退出关闭服务器链接
* */
public
void ftpLogOut() {
if (null !=
this.ftpClient &&
this.ftpClient.isConnected()) {
try {
boolean reuslt =
this.ftpClient.logout();//
退出FTP服务器
if (reuslt) {
System.out.println("成功退出服务器");
}
}catch(IOException e) {
e.printStackTrace();
System.out.println("退出FTP服务器异常!"
+ e.getMessage());
}finally{
try {
this.ftpClient.disconnect();//
关闭FTP服务器的连接
}catch(IOException e) {
e.printStackTrace();
System.out.println("关闭FTP服务器的连接异常!");
}
}
}
}
/***
* 上传Ftp文件
*
* @param localFile
* 当地文件
* @param romotUpLoadePath上传服务器路径
* -应该以/结束
* */
public
boolean uploadFile(FilelocalFile, String romotUpLoadePath) {
BufferedInputStreaminStream = null;
boolean success =
false;
try {
this.ftpClient.changeWorkingDirectory(romotUpLoadePath);//
改变工作路径
inStream= newBufferedInputStream(new FileInputStream(localFile));
System.out.println(localFile.getName()+
"开始上传.....");
success= this.ftpClient.storeFile(localFile.getName(),inStream);
if (success ==
true) {
System.out.println(localFile.getName()+
"上传成功");
return success;
}
}catch(FileNotFoundException e) {
e.printStackTrace();
System.out.println(localFile +
"未找到");
}catch(IOException e) {
e.printStackTrace();
}finally{
if (inStream !=
null) {
try {
inStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
return success;
}
/***
* 下载文件
*
* @param remoteFileName
* 待下载文件名称
* @param localDires
* 下载到当地那个路径下
* @param remoteDownLoadPath
* remoteFileName所在的路径
* */
public
boolean downloadFile(StringremoteFileName, String localDires,
StringremoteDownLoadPath) {
StringstrFilePath = localDires + remoteFileName;
BufferedOutputStreamoutStream = null;
boolean success =
false;
try {
this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream= newBufferedOutputStream(new FileOutputStream(
strFilePath));
System.out.println(remoteFileName+
"开始下载....");
success= this.ftpClient.retrieveFile(remoteFileName,outStream);
if (success ==
true) {
System.out.println(remoteFileName+
"成功下载到" + strFilePath);
return success;
}
}catch(Exception e) {
e.printStackTrace();
System.out.println(remoteFileName+
"下载失败");
}finally{
if (null != outStream) {
try {
outStream.flush();
outStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
if (success ==
false) {
System.out.println(remoteFileName+
"下载失败!!!");
}
return success;
}
/***
* @上传文件夹
* @param localDirectory
* 当地文件夹
* @param remoteDirectoryPath
* Ftp 服务器路径以目录"/"结束
* */
public
boolean uploadDirectory(StringlocalDirectory,
StringremoteDirectoryPath) {
Filesrc = newFile(localDirectory);
try {
remoteDirectoryPath= remoteDirectoryPath + src.getName() +
"//";
this.ftpClient.makeDirectory(remoteDirectoryPath);
// ftpClient.listDirectories();
}catch(IOException e) {
e.printStackTrace();
System.out.println(remoteDirectoryPath+
"目录创建失败");
}
File[]allFile = src.listFiles();
for (int currentFile = 0;currentFile < allFile.length; currentFile++) {
if(!allFile[currentFile].isDirectory()) {
StringsrcName = allFile[currentFile].getPath().toString();
uploadFile(new File(srcName),remoteDirectoryPath);
}
}
for (int currentFile = 0;currentFile < allFile.length; currentFile++) {
if(allFile[currentFile].isDirectory()) {
// 递归
uploadDirectory(allFile[currentFile].getPath().toString(),
remoteDirectoryPath);
}
}
return
true;
}
/***
* @下载文件夹
* @param localDirectoryPath本地地址
* @param remoteDirectory
* 远程文件夹
* */
public
booleandownLoadDirectory(String localDirectoryPath,
StringremoteDirectory) {
try {
StringfileName = newFile(remoteDirectory).getName();
localDirectoryPath= localDirectoryPath + fileName +
"/";
newFile(localDirectoryPath).mkdirs();
FTPFile[]allFile = this.ftpClient.listFiles(remoteDirectory);
for (int currentFile = 0;currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()){
downloadFile(allFile[currentFile].getName(),
localDirectoryPath,remoteDirectory);
}
}
for (int currentFile = 0;currentFile < allFile.length; currentFile++) {
//要去掉可能的当前目录,否则会导致死循环
if(allFile[currentFile].isDirectory()) {
if(allFile[currentFile].getName().equals(".") ||
allFile[currentFile].getName().equals("..")){
continue;
//要去掉可能的当前目录
}
else{
StringstrremoteDirectoryPath = remoteDirectory +
"/"
+allFile[currentFile].getName();
downLoadDirectory(localDirectoryPath,
strremoteDirectoryPath);
}
}
}
}catch(IOException e) {
e.printStackTrace();
System.out.println("下载文件夹失败");
return
false;
}
return
true;
}
// FtpClient的Set
和 Get
函数
public FTPClientgetFtpClient() {
return
ftpClient;
}
public
void setFtpClient(FTPClientftpClient) {
this.ftpClient = ftpClient;
}
public
static void main(String[] args)
throws IOException {
EasyFTPClientUsageftp = newEasyFTPClientUsage("192.168.1.1", 21,
"fanfangming","ffm");
ftp.ftpLogin();
//上传单个文件
ftp.uploadFile(new File("D:/ffm83/ffm83.txt"),"/ftpFile/");
// 上传文件夹
ftp.uploadDirectory("D:/ffm83/","/ftpFile/");
// 下载文件夹
ftp.downLoadDirectory("D:/ffm83/tmp/","/ftpFile/ffm83/");
ftp.ftpLogOut();
}
}
运行结果如下:
恭喜fanfangming成功登陆FTP服务器:192.168.19.13
ffm83.txt开始上传.....
ffm83.txt上传成功
…
不同的操作系统可能会有一些路径上的差异,需要注意。
下面的代码包括 FTP登陆,上传文件,上传文件夹,下载,退出登陆 五个功能模块。
package test.ffm83.commons.net.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* 通过commons net中的FTP包进行FTP的简单操作.FTP登陆,上传文件,上传文件夹,下载,退出登陆
* @author范芳铭
*/
public
classEasyFTPClientUsage {
private FTPClient
ftpClient;
private String
strIp;
private
int intPort;
private String
user;
private String
password;
/* *
* Ftp构造函数
*/
publicEasyFTPClientUsage(String strIp,
int intPort, String user,
StringPassword) {
this.strIp = strIp;
this.intPort = intPort;
this.user = user;
this.password = Password;
this.ftpClient =
new FTPClient();
}
/**
* @return判断是否登入成功
* */
public
boolean ftpLogin() {
boolean isLogin =
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服务器连接回答
int reply =
this.ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)){
this.ftpClient.disconnect();
System.out.println("登录FTP服务失败!");
return isLogin;
}
this.ftpClient.login(this.user,
this.password);
// 设置传输协议
this.ftpClient.enterLocalPassiveMode();
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
System.out.println("恭喜" +
this.user +
"成功登陆FTP服务器:" +
this.strIp );
isLogin= true;
}catch(Exception e) {
e.printStackTrace();
System.out.println(this.user +
"登录FTP服务失败!" + e.getMessage());
}
this.ftpClient.setBufferSize(1024 *2);
this.ftpClient.setDataTimeout(30 *1000);
return isLogin;
}
/**
* @退出关闭服务器链接
* */
public
void ftpLogOut() {
if (null !=
this.ftpClient &&
this.ftpClient.isConnected()) {
try {
boolean reuslt =
this.ftpClient.logout();//
退出FTP服务器
if (reuslt) {
System.out.println("成功退出服务器");
}
}catch(IOException e) {
e.printStackTrace();
System.out.println("退出FTP服务器异常!"
+ e.getMessage());
}finally{
try {
this.ftpClient.disconnect();//
关闭FTP服务器的连接
}catch(IOException e) {
e.printStackTrace();
System.out.println("关闭FTP服务器的连接异常!");
}
}
}
}
/***
* 上传Ftp文件
*
* @param localFile
* 当地文件
* @param romotUpLoadePath上传服务器路径
* -应该以/结束
* */
public
boolean uploadFile(FilelocalFile, String romotUpLoadePath) {
BufferedInputStreaminStream = null;
boolean success =
false;
try {
this.ftpClient.changeWorkingDirectory(romotUpLoadePath);//
改变工作路径
inStream= newBufferedInputStream(new FileInputStream(localFile));
System.out.println(localFile.getName()+
"开始上传.....");
success= this.ftpClient.storeFile(localFile.getName(),inStream);
if (success ==
true) {
System.out.println(localFile.getName()+
"上传成功");
return success;
}
}catch(FileNotFoundException e) {
e.printStackTrace();
System.out.println(localFile +
"未找到");
}catch(IOException e) {
e.printStackTrace();
}finally{
if (inStream !=
null) {
try {
inStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
return success;
}
/***
* 下载文件
*
* @param remoteFileName
* 待下载文件名称
* @param localDires
* 下载到当地那个路径下
* @param remoteDownLoadPath
* remoteFileName所在的路径
* */
public
boolean downloadFile(StringremoteFileName, String localDires,
StringremoteDownLoadPath) {
StringstrFilePath = localDires + remoteFileName;
BufferedOutputStreamoutStream = null;
boolean success =
false;
try {
this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream= newBufferedOutputStream(new FileOutputStream(
strFilePath));
System.out.println(remoteFileName+
"开始下载....");
success= this.ftpClient.retrieveFile(remoteFileName,outStream);
if (success ==
true) {
System.out.println(remoteFileName+
"成功下载到" + strFilePath);
return success;
}
}catch(Exception e) {
e.printStackTrace();
System.out.println(remoteFileName+
"下载失败");
}finally{
if (null != outStream) {
try {
outStream.flush();
outStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
if (success ==
false) {
System.out.println(remoteFileName+
"下载失败!!!");
}
return success;
}
/***
* @上传文件夹
* @param localDirectory
* 当地文件夹
* @param remoteDirectoryPath
* Ftp 服务器路径以目录"/"结束
* */
public
boolean uploadDirectory(StringlocalDirectory,
StringremoteDirectoryPath) {
Filesrc = newFile(localDirectory);
try {
remoteDirectoryPath= remoteDirectoryPath + src.getName() +
"//";
this.ftpClient.makeDirectory(remoteDirectoryPath);
// ftpClient.listDirectories();
}catch(IOException e) {
e.printStackTrace();
System.out.println(remoteDirectoryPath+
"目录创建失败");
}
File[]allFile = src.listFiles();
for (int currentFile = 0;currentFile < allFile.length; currentFile++) {
if(!allFile[currentFile].isDirectory()) {
StringsrcName = allFile[currentFile].getPath().toString();
uploadFile(new File(srcName),remoteDirectoryPath);
}
}
for (int currentFile = 0;currentFile < allFile.length; currentFile++) {
if(allFile[currentFile].isDirectory()) {
// 递归
uploadDirectory(allFile[currentFile].getPath().toString(),
remoteDirectoryPath);
}
}
return
true;
}
/***
* @下载文件夹
* @param localDirectoryPath本地地址
* @param remoteDirectory
* 远程文件夹
* */
public
booleandownLoadDirectory(String localDirectoryPath,
StringremoteDirectory) {
try {
StringfileName = newFile(remoteDirectory).getName();
localDirectoryPath= localDirectoryPath + fileName +
"/";
newFile(localDirectoryPath).mkdirs();
FTPFile[]allFile = this.ftpClient.listFiles(remoteDirectory);
for (int currentFile = 0;currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()){
downloadFile(allFile[currentFile].getName(),
localDirectoryPath,remoteDirectory);
}
}
for (int currentFile = 0;currentFile < allFile.length; currentFile++) {
//要去掉可能的当前目录,否则会导致死循环
if(allFile[currentFile].isDirectory()) {
if(allFile[currentFile].getName().equals(".") ||
allFile[currentFile].getName().equals("..")){
continue;
//要去掉可能的当前目录
}
else{
StringstrremoteDirectoryPath = remoteDirectory +
"/"
+allFile[currentFile].getName();
downLoadDirectory(localDirectoryPath,
strremoteDirectoryPath);
}
}
}
}catch(IOException e) {
e.printStackTrace();
System.out.println("下载文件夹失败");
return
false;
}
return
true;
}
// FtpClient的Set
和 Get
函数
public FTPClientgetFtpClient() {
return
ftpClient;
}
public
void setFtpClient(FTPClientftpClient) {
this.ftpClient = ftpClient;
}
public
static void main(String[] args)
throws IOException {
EasyFTPClientUsageftp = newEasyFTPClientUsage("192.168.1.1", 21,
"fanfangming","ffm");
ftp.ftpLogin();
//上传单个文件
ftp.uploadFile(new File("D:/ffm83/ffm83.txt"),"/ftpFile/");
// 上传文件夹
ftp.uploadDirectory("D:/ffm83/","/ftpFile/");
// 下载文件夹
ftp.downLoadDirectory("D:/ffm83/tmp/","/ftpFile/ffm83/");
ftp.ftpLogOut();
}
}
运行结果如下:
恭喜fanfangming成功登陆FTP服务器:192.168.19.13
ffm83.txt开始上传.....
ffm83.txt上传成功
…
相关文章推荐
- 利用org.apache.commons.net.ftp实现ftp下载,解决中文文件名乱码问题
- 使用Apache 的commons-net 包实现FTP上传下载小结
- Android 利用commons-net-3.3实现ftp上传下载
- 利用Apache的commons-net实现FTP的文件读取、上传、下载、删除和移动功能
- 利用Apache commons net 包实现简单的POP3邮件
- 【FTP】org.apache.commons.net.ftp.FTPClient实现复杂的上传下载,操作目录,处理编码
- Android开发 之 利用commons-net-3.0.1.jar包实现FTP上传下载功能
- 【FTP】使用org.apache.commons.net.ftp.FTPClient 实现FTP的上传下载
- 利用org.apache.commons.net.ftp包实现一个简单的ftp客户端实用类
- 使用apache的commons-net-3.1.jar实现FTP上传
- ASP.NET利用HttpHandler实现多扩展名文件下载
- apache的commons-fileupload实现文件上传,下载
- apache-commons-net Ftp 进行文件、文件夹的上传下载及日志的输出
- Java 利用Apache Commons Net 实现 FTP文件上传下载
- Net网络通讯编程[利用Socket实现字串、文件、序列化对象传输]--前面6篇博文全部源代码下载地址
- ASP.NET利用HttpHandler实现多扩展名文件下载 [转]
- java中利用commons-net上传下载文件
- apache的commons-fileupload实现文件上传,下载
- 使用org.apache.commons.net.ftp包开发FTP客户端,实现进度汇报,实现断点续
- apache的org.apache.commons.net包 下载文件问题总结