apache-commons-net Ftp 进行文件、文件夹的上传下载及日志的输出
用到了apache 的 commons-net-3.0.1.jar 和 log4j-1.2.15.jar 这连个jar包
JAVA 代码如下:
package com.bjut.edu.cn.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; import org.apache.log4j.Logger; public class Ftp {
private FTPClient ftpClient;
private String strIp;
private int intPort;
private String user;
private String password; private static Logger logger = Logger.getLogger(Ftp.class.getName()); /* *
* Ftp构造函数
*/
public Ftp(String strIp, int intPort, String user, String Password) {
this.strIp = strIp;
this.intPort = intPort;
this.user = user;
this.password = Password;
this.ftpClient = new FTPClient();
}
/**
* @return 判断是否登入成功
* */
public boolean ftpLogin() {
boolean isLogin = false;
FTPClientConfig ftpClientConfig = new FTPClientConfig();
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();
logger.error("登录FTP服务失败!");
return isLogin;
}
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 (Exception e) {
e.printStackTrace();
logger.error(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) {
logger.info("成功退出服务器");
}
} catch (IOException e) {
e.printStackTrace();
logger.warn("退出FTP服务器异常!" + e.getMessage());
} finally {
try {
this.ftpClient.disconnect();// 关闭FTP服务器的连接
} catch (IOException e) {
e.printStackTrace();
logger.warn("关闭FTP服务器的连接异常!");
}
}
}
} /***
* 上传Ftp文件
* @param localFile 当地文件
* @param romotUpLoadePath上传服务器路径 - 应该以/结束
* */
public boolean uploadFile(File localFile, String romotUpLoadePath) {
BufferedInputStream inStream = null;
boolean success = false;
try {
this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
inStream = new BufferedInputStream(new FileInputStream(localFile));
logger.info(localFile.getName() + "开始上传.....");
success = this.ftpClient.storeFile(localFile.getName(), inStream);
if (success == true) {
logger.info(localFile.getName() + "上传成功");
return success;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.error(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(String remoteFileName, String localDires,
String remoteDownLoadPath) {
String strFilePath = localDires + remoteFileName;
BufferedOutputStream outStream = null;
boolean success = false;
try {
this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream = new BufferedOutputStream(new FileOutputStream(
strFilePath));
logger.info(remoteFileName + "开始下载....");
success = this.ftpClient.retrieveFile(remoteFileName, outStream);
if (success == true) {
logger.info(remoteFileName + "成功下载到" + strFilePath);
return success;
}
} catch (Exception e) {
e.printStackTrace();
logger.error(remoteFileName + "下载失败");
} finally {
if (null != outStream) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (success == false) {
logger.error(remoteFileName + "下载失败!!!");
}
return success;
} /***
* @上传文件夹
* @param localDirectory
* 当地文件夹
* @param remoteDirectoryPath
* Ftp 服务器路径 以目录"/"结束
* */
public boolean uploadDirectory(String localDirectory,
String remoteDirectoryPath) {
File src = new File(localDirectory);
try {
remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
this.ftpClient.makeDirectory(remoteDirectoryPath);
// ftpClient.listDirectories();
} catch (IOException e) {
e.printStackTrace();
logger.info(remoteDirectoryPath + "目录创建失败");
}
File[] allFile = src.listFiles();
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
String srcName = 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 boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
try {
String fileName = new File(remoteDirectory).getName();
localDirectoryPath = localDirectoryPath + fileName + "//";
new File(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()) {
String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
}
}
} catch (IOException e) {
e.printStackTrace();
logger.info("下载文件夹失败");
return false;
}
return true;
}
// FtpClient的Set 和 Get 函数
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
} public static void main(String[] args) throws IOException {
Ftp ftp=new Ftp("10.3.15.1",21,"ghips","ghipsteam");
ftp.ftpLogin();
//上传文件夹
ftp.uploadDirectory("d://DataProtemp", "/home/data/");
//下载文件夹
ftp.downLoadDirectory("d://tmp//", "/home/data/DataProtemp");
ftp.ftpLogOut();
}
}
apache-commons-net Ftp 进行文件、文件夹的上传下载及日志的输出的更多相关文章
- java:工具(汉语转拼音,压缩包,EXCEL,JFrame窗口和文件选择器,SFTP上传下载,FTP工具类,SSH)
1.汉语转拼音: import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuP ...
- 需求-java web 能够实现整个文件夹的上传下载吗?
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...
- Linux shell:FTP(文件传输协议)上传下载命令
SecureCRT通过ftp将nmon上传,建立一个目录,用命令上传文件.[命令见下面] 或通过UE.SSH上传/下载,使用sftp建立链接. [通过cmd进入ftp服务器]先假设有一FTP服务器,F ...
- Win10 搭建FTP环境,并使用Java实现上传,下载,删除
测试的环境一般都是在自己电脑上面装的,现在一般都使用Win10开发 搭建FTP: 第一步:打开控制面板:点击程序 第二步: 第三步: 然后点击确认后等待完成 完成后在启动中找到IIS管理器 打开 在网 ...
- java web 能够实现整个文件夹的上传下载吗?
在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...
- [FTP] FTPClient--FTP操作帮助类,上传下载,文件,目录操作 (转载)
点击下载 FTPClient.zip 这个类是关于FTP客户端的操作1.构造函数 2.字段 服务器账户密码3.属性4.链接5.传输模式6.文件操作7.上传和下载8.目录操作9.内容函数看下面代码吧 / ...
- ftp org.apache.commons.net.ftp.FTPClient 判断文件是否存在
String path = "/SJPT/ONPUT/HMD_TEST/" ; FtpTool.getFTPClient().changeWorkingDirectory(path ...
- Java Web 项目的文件/文件夹上传下载
需求: 支持大文件批量上传(20G)和下载,同时需要保证上传期间用户电脑不出现卡死等体验: 内网百兆网络上传速度为12MB/S 服务器内存占用低 支持文件夹上传,文件夹中的文件数量达到1万个以上,且包 ...
- putty对Linux上传下载文件或文件夹
putty是一个开源软件,目前为止最新版本为0.70.对于文件或文件夹的上传下载,在Windows下它提供了pscp和psftp两个命令. (1).pscp pscp在命令提示符中使用,只要putty ...
随机推荐
- JAVA设计模式--strategy(策略者模式)
概念策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换.策略模式让算法独立于使用它的客户而独立变化.(原文:The Strategy Pattern defines a fa ...
- Windows Phone 显示长文本
文采不好,将就着看,见谅 思路最重要,故本文不提供源码下载 参考项目: http://www.windowsphone.com/zh-cn/store/app/%E5%BF%83%E7%90%86fm ...
- ElasticSearch-PHP的API使用(二)
1:索引内的一个文档的创建(相当表记录的添加) 比如:要添加一条记录 INSERT INTO blog(title,content,add_time) VALUES('ElasticSearch-PH ...
- YUM软件管理
YUM是一个RPM的前端程序,主要目的是设计用来解决RPM的依赖关系的问题,而不用手动安装所依赖的所有软件.它使用仓库保存管理RPM软件包,仓库的配置文件保存在/etc/yum.repos.d/目录下 ...
- Js/Ajax中发送HttpPost请求调用WebService
1) WebService中的方法 [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(Confo ...
- 浏览器内置Console函数使用详解
浏览器内置Console函数比较好用:Chrome 和 FireFox(Firebug插件) 利用此功能可以像直接在面板里面运行JS一样(写法不同而已) 一.显示信息的命令 Firebug内置一个co ...
- Show Users Assigned to a Specific Role
In a previous post I showed you how to know what Roles are assigned to a specific user. But here is ...
- [leetcode]_Same Tree
第一次遇见Tree的题,拿到心慌,网上查了解题思路.写完就三行.. 最近努力学习一句话,学会喜欢自己. 题目:give two tree , you must judge if they are th ...
- 史上最全Vim快捷键键位图(入门到进阶)
经典版 下面这个键位图应该是大家最常看见的经典版了. 对应的简体中文版 其实经典版是一系列的入门教程键位图的组合结果,下面是不同编辑模式下的键位图. 入门版 基本操作的入门版. 进阶版 增强版 下图是 ...
- Sublime Text 快捷键
ctrl+shift+t:重新打开最近关闭文件 快捷键 功能 ctrl+shift+n 打开新Sublime ctrl+shift+w 关闭Sublime,关闭所有打开文件 ctrl+shift+t ...