FTP之二
- username=admin
- password=123
- ip=192.168.14.117
- port=21
参考:http://blog.csdn.net/yelove1990/article/details/41245039
实现类
- package com.util;
- import java.io.*;
- import java.net.SocketException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Properties;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.apache.commons.net.ftp.FTP;
- 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;
- public class FTPClientTest {
- private static final Log logger = LogFactory.getLog(FTPClientTest.class);
- private String userName; //FTP 登录用户名
- private String password; //FTP 登录密码
- private String ip; //FTP 服务器地址IP地址
- private int port; //FTP 端口
- private Properties property = null; //属性集
- private String configFile = "conf/application.properties"; //配置文件的路径名
- private FTPClient ftpClient = null; //FTP 客户端代理
- //时间格式化
- private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
- //FTP状态码
- public int i = 1;
- /**
- * 连接到服务器
- *
- * @return true 连接服务器成功,false 连接服务器失败
- */
- public boolean connectServer() {
- boolean flag = true;
- if (ftpClient == null) {
- int reply;
- try {
- if(setArg(configFile)){
- ftpClient = new FTPClient();
- ftpClient.setControlEncoding("GBK");
- //ftpClient.configure(getFtpConfig());
- ftpClient.connect(ip,port);
- ftpClient.login(userName, password);
- reply = ftpClient.getReplyCode();
- ftpClient.setDataTimeout(120000);
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftpClient.disconnect();
- logger.debug("FTP 服务拒绝连接!");
- flag = false;
- }
- i++;
- }else{
- flag = false;
- }
- } catch (SocketException e) {
- flag = false;
- e.printStackTrace();
- logger.debug("登录ftp服务器 " + ip + " 失败,连接超时!");
- } catch (IOException e) {
- flag = false;
- e.printStackTrace();
- logger.debug("登录ftp服务器 " + ip + " 失败,FTP服务器无法打开!");
- }
- }
- return flag;
- }
- /**
- * 上传文件
- *
- * @param remoteFile
- * 远程文件路径,支持多级目录嵌套
- * @param localFile
- * 本地文件名称,绝对路径
- *
- */
- public boolean uploadFile(String remoteFile, File localFile)
- throws IOException {
- boolean flag = false;
- InputStream in = new FileInputStream(localFile);
- String remote = new String(remoteFile.getBytes("GBK"),"iso-8859-1");
- if(ftpClient.storeFile(remote, in)){
- flag = true;
- logger.debug(localFile.getAbsolutePath()+"上传文件成功!");
- }else{
- logger.debug(localFile.getAbsolutePath()+"上传文件失败!");
- }
- in.close();
- return flag;
- }
- /**
- * 上传单个文件,并重命名
- *
- * @param localFile--本地文件路径
- * @param localRootFile--本地文件父文件夹路径
- * @param distFolder--新的文件名,可以命名为空""
- * @return true 上传成功,false 上传失败
- * @throws IOException
- */
- public boolean uploadFile(String local, String remote) throws IOException {
- boolean flag = true;
- String remoteFileName = remote;
- if (remote.contains("/")) {
- remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
- // 创建服务器远程目录结构,创建失败直接返回
- if (!CreateDirecroty(remote)) {
- return false;
- }
- }
- FTPFile[] files = ftpClient.listFiles(new String(remoteFileName));
- File f = new File(local);
- if(!uploadFile(remoteFileName, f)){
- flag = false;
- }
- return flag;
- }
- /**
- * 上传文件夹内的所有文件
- *
- *
- * @param filename
- * 本地文件夹绝对路径
- * @param uploadpath
- * 上传到FTP的路径,形式为/或/dir1/dir2/../
- * @return true 上传成功,false 上传失败
- * @throws IOException
- */
- public List uploadManyFile(String filename, String uploadpath) {
- boolean flag = true;
- List l = new ArrayList();
- StringBuffer strBuf = new StringBuffer();
- int n = 0; //上传失败的文件个数
- int m = 0; //上传成功的文件个数
- try {
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- ftpClient.enterLocalPassiveMode();
- ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
- ftpClient.changeWorkingDirectory("/");
- File file = new File(filename);
- File fileList[] = file.listFiles();
- for (File upfile : fileList) {
- if (upfile.isDirectory()) {
- uploadManyFile(upfile.getAbsoluteFile().toString(),uploadpath);
- } else {
- String local = upfile.getCanonicalPath().replaceAll("\\\\","/");
- String remote = uploadpath.replaceAll("\\\\","/") + local.substring(local.indexOf("/") + 1);
- flag = uploadFile(local, remote);
- ftpClient.changeWorkingDirectory("/");
- }
- if (!flag) {
- n++;
- strBuf.append(upfile.getName() + ",");
- logger.debug("文件[" + upfile.getName() + "]上传失败");
- } else{
- m++;
- }
- }
- l.add(0, n);
- l.add(1, m);
- l.add(2, strBuf.toString());
- } catch (NullPointerException e) {
- e.printStackTrace();
- logger.debug("本地文件上传失败!找不到上传文件!", e);
- } catch (Exception e) {
- e.printStackTrace();
- logger.debug("本地文件上传失败!", e);
- }
- return l;
- }
- /**
- * 下载文件
- *
- * @param remoteFileName --服务器上的文件名
- * @param localFileName--本地文件名
- * @return true 下载成功,false 下载失败
- */
- public boolean loadFile(String remoteFileName, String localFileName) {
- boolean flag = true;
- // 下载文件
- BufferedOutputStream buffOut = null;
- try {
- buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));
- flag = ftpClient.retrieveFile(remoteFileName, buffOut);
- } catch (Exception e) {
- e.printStackTrace();
- logger.debug("本地文件下载失败!", e);
- } finally {
- try {
- if (buffOut != null)
- buffOut.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return flag;
- }
- /**
- * 删除一个文件
- */
- public boolean deleteFile(String filename) {
- boolean flag = true;
- try {
- flag = ftpClient.deleteFile(filename);
- if (flag) {
- logger.debug("删除文件"+filename+"成功!");
- } else {
- logger.debug("删除文件"+filename+"成功!");
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- return flag;
- }
- /**
- * 删除目录
- */
- public void deleteDirectory(String pathname) {
- try {
- File file = new File(pathname);
- if (file.isDirectory()) {
- File file2[] = file.listFiles();
- } else {
- deleteFile(pathname);
- }
- ftpClient.removeDirectory(pathname);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- /**
- * 删除空目录
- */
- public void deleteEmptyDirectory(String pathname) {
- try {
- ftpClient.removeDirectory(pathname);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- /**
- * 列出服务器上文件和目录
- *
- * @param regStr --匹配的正则表达式
- */
- public void listRemoteFiles(String regStr) {
- try {
- String files[] = ftpClient.listNames(regStr);
- if (files == null || files.length == 0)
- logger.debug("没有任何文件!");
- else {
- for (int i = 0; i < files.length; i++) {
- System.out.println(files[i]);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 列出Ftp服务器上的所有文件和目录
- */
- public void listRemoteAllFiles() {
- try {
- String[] names = ftpClient.listNames();
- for (int i = 0; i < names.length; i++) {
- System.out.println(names[i]);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 关闭连接
- */
- public void closeConnect() {
- try {
- if (ftpClient != null) {
- ftpClient.logout();
- ftpClient.disconnect();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 设置传输文件的类型[文本文件或者二进制文件]
- *
- * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE
- *
- */
- public void setFileType(int fileType) {
- try {
- ftpClient.setFileType(fileType);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 设置参数
- *
- * @param configFile --参数的配置文件
- */
- private boolean setArg(String configFile) {
- boolean flag = true;
- property = new Properties();
- BufferedInputStream inBuff = null;
- try {
- inBuff = new BufferedInputStream(new FileInputStream(getClass().getResource("/").getPath() + configFile));
- property.load(inBuff);
- userName = property.getProperty("username");
- password = property.getProperty("password");
- ip = property.getProperty("ip");
- port = Integer.parseInt(property.getProperty("port"));
- } catch (FileNotFoundException e1) {
- flag = false;
- logger.debug("配置文件 " + configFile + " 不存在!");
- } catch (IOException e) {
- flag = false;
- logger.debug("配置文件 " + configFile + " 无法读取!");
- }
- return flag;
- }
- /**
- * 进入到服务器的某个目录下
- *
- * @param directory
- */
- public boolean changeWorkingDirectory(String directory) {
- boolean flag = true;
- try {
- flag = ftpClient.changeWorkingDirectory(directory);
- if (flag) {
- logger.debug("进入文件夹"+ directory + " 成功!");
- } else {
- logger.debug("进入文件夹"+ directory + " 失败!");
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- return flag;
- }
- /**
- * 返回到上一层目录
- */
- public void changeToParentDirectory() {
- try {
- ftpClient.changeToParentDirectory();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- /**
- * 重命名文件
- *
- * @param oldFileName --原文件名
- * @param newFileName --新文件名
- */
- public void renameFile(String oldFileName, String newFileName) {
- try {
- ftpClient.rename(oldFileName, newFileName);
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- /**
- * 设置FTP客服端的配置--一般可以不设置
- *
- * @return ftpConfig
- */
- private FTPClientConfig getFtpConfig() {
- FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
- ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
- return ftpConfig;
- }
- /**
- * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码
- *
- * @param obj
- * @return ""
- */
- private String iso8859togbk(Object obj) {
- try {
- if (obj == null)
- return "";
- else
- return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
- } catch (Exception e) {
- return "";
- }
- }
- /**
- * 在服务器上创建一个文件夹
- *
- * @param dir 文件夹名称,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>...
- */
- public boolean makeDirectory(String dir) {
- boolean flag = true;
- try {
- flag = ftpClient.makeDirectory(dir);
- if (flag) {
- logger.debug("创建文件夹"+ dir + " 成功!");
- } else {
- logger.debug("创建文件夹"+ dir + " 失败!");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return flag;
- }
- // 检查路径是否存在,存在返回true,否则false
- public boolean existFile(String path) throws IOException {
- boolean flag = false;
- FTPFile[] ftpFileArr = ftpClient.listFiles(path);
- /* for (FTPFile ftpFile : ftpFileArr) {
- if (ftpFile.isDirectory()
- && ftpFile.getName().equalsIgnoreCase(path)) {
- flag = true;
- break;
- }
- } */
- if(ftpFileArr.length > 0){
- flag = true;
- }
- return flag;
- }
- /**
- * 递归创建远程服务器目录
- *
- * @param remote
- * 远程服务器文件绝对路径
- *
- * @return 目录创建是否成功
- * @throws IOException
- */
- public boolean CreateDirecroty(String remote) throws IOException {
- boolean success = true;
- String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
- // 如果远程目录不存在,则递归创建远程服务器目录
- if (!directory.equalsIgnoreCase("/")&& !changeWorkingDirectory(new String(directory))) {
- int start = 0;
- int end = 0;
- if (directory.startsWith("/")) {
- start = 1;
- } else {
- start = 0;
- }
- end = directory.indexOf("/", start);
- while (true) {
- String subDirectory = new String(remote.substring(start, end).getBytes("GBK"),"iso-8859-1");
- if (changeWorkingDirectory(subDirectory)) {
- if (makeDirectory(subDirectory)) {
- changeWorkingDirectory(subDirectory);
- } else {
- logger.debug("创建目录["+subDirectory+"]失败");
- System.out.println("创建目录["+subDirectory+"]失败");
- success = false;
- return success;
- }
- }
- start = end + 1;
- end = directory.indexOf("/", start);
- // 检查所有目录是否创建完毕
- if (end <= start) {
- break;
- }
- }
- }
- return success;
- }
- public static void main(String[] args) {
- FTPClientTest ftpClient = new FTPClientTest();
- if(ftpClient.connectServer()){
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输二进制文件
- ftpClient.uploadManyFile("H:\\d", "/d/");
- ftpClient.closeConnect();// 关闭连接
- }
- }
- }
FTP之二的更多相关文章
- 8、FTP,二种文本传输模式
一.基本知识 1. FTP是 TCP/IP协议族 的协议之一,简称文件传输协议,主要用于远距离文件传输,如文件的上传和下载 2. 下面都是以VSFTP服务器为例 VSFTP服务器的用户有三种形式: 匿 ...
- 使用c++实现一个FTP客户端(二)
接上篇http://www.cnblogs.com/jzincnblogs/p/5213978.html,这篇主要记录编程方面的重点. 客户端使用了Windows Socket提供的API,支持上传. ...
- linux配置ftp
参考: http://www.cnblogs.com/acpp/archive/2010/02/08/1665876.html http://blog.csdn.net/huzhenwei/artic ...
- FTP基础知识 FTP port(主动模式) pasv(被动模式) 及如何映射FTP
您是否正准备搭建自己的FTP网站?您知道FTP协议的工作机制吗?您知道什么是PORT方式?什么是PASV方式吗?如果您不知道,或没有完全掌握,请您坐下来,花一点点时间,细心读完这篇文章.所谓磨刀不误砍 ...
- [转] Linux学习之CentOS(三十六)--FTP服务原理及vsfptd的安装、配置
本篇随笔将讲解FTP服务的原理以及vsfptd这个最常用的FTP服务程序的安装与配置... 一.FTP服务原理 FTP(File Transfer Protocol)是一个非常古老并且应用十分广泛的文 ...
- linux Centos 6.5 FTP服务原理及vsfptd的安装、配置(转)
本篇随笔将讲解FTP服务的原理以及vsfptd这个最常用的FTP服务程序的安装与配置... 一.FTP服务原理 FTP(File Transfer Protocol)是一个非常古老并且应用十分广泛的文 ...
- 【应用】:shell crontab定时生成oracle表的数据到txt文件,并上传到ftp
一.本人环境描述 1.oracle服务端装在win7 32位上,oracle版本为10.2.0.1.0 2.Linux为centos6.5 32位,安装在Oracle VM Vir ...
- Sftp和ftp 差别、工作原理等(汇总ing)
Sftp和ftp over ssh2的差别 近期使用SecureFx,涉及了两个不同的安全文件传输协议: -sftp -ftp over SSH2 这两种协议是不同的.sftp是ssh内含的协议,仅仅 ...
- wind7下搭建ftp服务器
一.首先在本地机器上创建一个用户!这些用户是用来登录到FTP的!我的电脑右键->控制面板->管理工具->计算机管理->本地用户和组->用户->“右键”新建用户-&g ...
随机推荐
- c# WebApi之解决跨域问题:Cors
什么是跨域问题 出于安全考虑,浏览器会限制脚本中发起的跨站请求,浏览器要求JavaScript或Cookie只能访问同域下的内容.由于这个原因,我们不同站点之间的数据访问会被拒绝. Cors解决跨域问 ...
- linux:awk修改输出分隔符
file1的内容如下: a b c d e f g h 现在想要修改成 a b c:d e f g:h 则需要用到如下命令: awk -F " " '{print $1,$2,$3 ...
- ubuntu下 pthread_mutex_init man中查不到
问题: 如题所述,包括pthread_mutex_init 和 pthread_mutex_lock 这些函数都找不到 解决办法: 安装manpages:manpages-posix-dev Mint ...
- 将Excel导出为SQL语句
需求说明:公司做项目前进行需求分析,确定表结构后需要建表,如果照着表格去敲,那就太麻烦了,所以想到了自动生成SQL语句. 思路大概就是:解析Excel,拼接SQL语句,输出SQL文件. 第三方jar包 ...
- npmrc npm配置文件
一.全局 这个文件在全局会放在/users/${yourname}/.npmrc 里面最重要的是registry,npm的源 二.项目 项目里面如果和package.json同级存放了这个.npmrc ...
- flask session
flask session工作机制: 把敏感数据经过加密后放入到‘session’中,然后在把'session'存放到cookie中,下次请求的时候,再从浏览器发送过来的cookie中读取sessio ...
- centos 7 上zabbix 3.0 服务端安装
zabbix服务端安装 安装完毕mysql-5.6.php5.6 mysql-5.6安装:https://www.cnblogs.com/xzlive/p/9771642.html 创建zabbix ...
- JAVA-序列化深拷贝对象
序列化拷贝方法 @SuppressWarnings("unchecked") public static <T extends Serializable> T clon ...
- UEditor js动态创建和textarea中渲染【原】
UEditor动态创建和textarea中渲染 http://ueditor.baidu.com/website/examples/textareaDemo.html <!DOCTYPE> ...
- vs code配置git
在项目目录执行 git init 修改.git文件夹下的config文件 [core] repositoryformatversion = 0 filemode = false bare = fals ...