package net.util.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient; /**
* need commons-net-3.5.jar
*/
public class FtpHelper { private String host;//ip地址
private Integer port;//端口号
private String userName;//用户名
private String pwd;//密码
//private String homePath;//aaa路径
private String charSet = "utf-8";
// 默认超时, 毫秒
private long timeout = 30*1000; public FTPClient ftpClient = null; public FtpHelper(){
init();
}
public FtpHelper(boolean ftps){
init(ftps);
} /**
* ftp 初始化
*/
public void init(){
init(false);
}
public void init(boolean ftps){
close();
if(ftps==true){
ftpClient = new FTPSClient(true);
}
else{
ftpClient=new FTPClient();
} // 默认编码
ftpClient.setControlEncoding(charSet); //ftpClient.setBufferSize(524288);
//ftpClient.enterLocalPassiveMode();
// 毫秒计时
ftpClient.setDefaultTimeout((int) timeout);
ftpClient.setConnectTimeout((int) timeout);
//ftpClient.setSoTimeout((int) timeout);
//ftpClient.setDataTimeout(timeout);
} /**
* 获取ftp连接
* @return
* @throws Exception
*/
public boolean connect(String host, Integer port, String userName, String pwd) throws Exception{
this.host = host;
this.port = port;
this.userName= userName;
this.pwd = pwd;
return connect();
}
public boolean connect() throws Exception{
boolean flag=false;
int reply;
if (port==null) {
ftpClient.connect(host,21);
}else{
ftpClient.connect(host, port);
} flag = ftpClient.login(userName, pwd);
if(flag==false)
return flag; // 服务器是否响应
reply = ftpClient.getReplyCode();
if (FTPReply.isPositiveCompletion(reply)==false) {
flag = false;
ftpClient.disconnect();
return flag;
} // 默认文件格式
ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); return flag;
} /**
* 关闭ftp连接
*/
public void close(){
if (ftpClient==null || ftpClient.isConnected()==false) {
ftpClient = null;
return;
}
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
LogHelper.logger.warn("",e);
}
ftpClient = null;
} /*
* ftp 多种开关函数
*/
public FTPClient getClient(){
return ftpClient;
}
public void setControlEncoding(String encoding) {
this.charSet = encoding;
ftpClient.setControlEncoding(encoding);
}
public void enterLocalPassiveMode(){
ftpClient.enterLocalPassiveMode();
}
public void enterLocalActiveMode(){
ftpClient.enterLocalActiveMode();
}
// 毫秒计时
public void setDefaultTimeout(int timeout) {
ftpClient.setDefaultTimeout(timeout);
}
// 毫秒计时
// public void setConnectTimeout(int connectTimeout) {
// ftpClient.setConnectTimeout(connectTimeout);
// }
// 毫秒计时
public void setDataTimeout(int timeout) {
ftpClient.setDataTimeout(timeout);
}
public void setBufferSize(int bufSize) {
ftpClient.setBufferSize(bufSize);
}
/**
* 传输格式
* @param mode: FTPClient.BINARY_FILE_TYPE
* @return
* @throws IOException
*/
public boolean setFileTransferMode(int mode) throws IOException{
return ftpClient.setFileTransferMode(mode);
}
/**
* 文件格式
* @param mode: FTPClient.BINARY_FILE_TYPE
* @return
* @throws IOException
*/
public boolean setFileType(int mode) throws IOException {
return ftpClient.setFileType(mode); }
/*
* ftp 多种开关函数
*/ /**
* ftp创建目录
* @param path
* @return
* @throws IOException
*/
public boolean createDir(String path) throws IOException{
boolean bl = false;
String pwd = "/";
try {
pwd = ftpClient.printWorkingDirectory();
} catch (IOException e) {
LogHelper.logger.warn("",e);
}
if(path.endsWith("/")==false){
path = path + "/";
}
int fromIndex = 0;
while(true){
int start = path.indexOf("/", fromIndex);
if(start<0)
break;
fromIndex = start;
String curPath = path.substring(0, fromIndex+1);
//System.out.println(curPath);
bl = ftpClient.changeWorkingDirectory(curPath);
if(bl==false){
bl = ftpClient.makeDirectory(curPath);
}
if(bl==false)
break;
fromIndex = fromIndex + 1;
}
ftpClient.changeWorkingDirectory(pwd);
return bl;
} /**
* ftp上传文件或文件夹
* @param srcPath: 本地目录或文件
* @param dstPath: ftp目录或文件
* @throws Exception
*/
public void upload(String localPath, String ftpPath) throws Exception{
File file = new File(localPath);
if (file.isDirectory()) {
createDir(ftpPath);
String[] files=file.list();
for(String fileName : files){
String subLocalPath = PathUtil.CombineUrl(localPath, fileName);
String subFtpPath = PathUtil.CombineUrl(ftpPath, fileName);
upload(subLocalPath, subFtpPath);
}
}
else{
FileInputStream localInput = null;
try {
//ftpClient.enterLocalPassiveMode();
String dirPath = new File(ftpPath).getParent();
dirPath = dirPath.replace("\\", "/");
createDir(dirPath);
localInput = new FileInputStream(file);
if(ftpClient.storeFile(ftpPath, localInput)==false){
LogHelper.logger.error("ftp upload file error: "+localPath);
}
}
catch (Exception e) {
LogHelper.logger.warn("",e);
}
finally{
try {
if(localInput!=null)
localInput.close();
} catch (Exception e) {}
}
}
}
/**
* ftp单文件上传
* @param localPath
* @param ftpPath
* @return
*/
public boolean uploadFile(String localPath, String ftpPath){
boolean bl = false;
File file = new File(localPath);
if (file.isFile()) {
FileInputStream localInput = null;
try {
//String tmpPath = ftpPath + ".tmp";
//ftpClient.enterLocalPassiveMode();
String dirPath = new File(ftpPath).getParent();
dirPath = dirPath.replace("\\", "/");
createDir(dirPath);
localInput = new FileInputStream(file);
if(ftpClient.storeFile(ftpPath, localInput)==false){
bl = false;
LogHelper.logger.error("ftp upload file error: "+localPath);
}
else{
//bl = ftpClient.rename(tmpPath, ftpPath);
bl = true;
}
}
catch (Exception e) {
LogHelper.logger.warn("",e);
}
finally{
try {
if(localInput!=null)
localInput.close();
} catch (Exception e) {}
}
}
return bl;
} /**
* ftp下载文件或目录
* @param ftpPath: ftp远程目录或文件
* @param localPath: 本地保存目录或文件
* @param isFile: ftppath是文件或目录
* @throws Exception
*/
public void down(String ftpPath, String localPath, boolean isFile) throws Exception{
if(isFile==true){
FileOutputStream localFos = null;
try {
//ftpClient.enterLocalPassiveMode();
String dirPath = new File(localPath).getParent();
FileUtil.createDir(dirPath);
File file = new File(localPath);
localFos = new FileOutputStream(file);
if(ftpClient.retrieveFile(ftpPath, localFos)==false){
LogHelper.logger.error("ftp down file error: "+ftpPath);
}
}
catch (Exception e) {
LogHelper.logger.warn("",e);
}
finally{
try {
if(localFos!=null)
localFos.close();
} catch (Exception e) {}
}
}
// 目录处理
else{
FileUtil.createDir(localPath);
FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath);
for (int j=0; j<ftpFiles.length; j++) {
FTPFile ftpFile = ftpFiles[j];
String subFtpPath = PathUtil.CombineUrl(ftpPath, ftpFile.getName());
String subLocalPath = PathUtil.CombineUrl(localPath, ftpFile.getName());
if(ftpFile.isFile()==true){
down(subFtpPath, subLocalPath, true);
}
else{
down(subFtpPath, subLocalPath, false);
}
}
}
}
/**
* ftp单文件下载
* @param ftpPath
* @param localPath
* @return
*/
public boolean downFile(String ftpPath, String localPath) {
boolean bl = false;
FileOutputStream localFos = null;
try {
//ftpClient.enterLocalPassiveMode();
FileUtil.createDir(localPath, true);
File file = new File(localPath);
localFos = new FileOutputStream(file);
if(ftpClient.retrieveFile(ftpPath, localFos)==false){
LogHelper.logger.error("ftp down file error: "+ftpPath);
}
else{
bl = true;
}
}
catch (Exception e) {
LogHelper.logger.warn("",e);
}
finally{
try {
if(localFos!=null)
localFos.close();
} catch (Exception e) {}
}
return bl;
} /**
* 判断路径是否为ftp文件
* @param ftpPath
* @return
* @throws IOException
*/
public boolean isFile(String ftpPath) throws IOException{
if(ftpPath==null || ftpPath.endsWith("/"))
return false;
File f = new File(ftpPath);
String lastName = f.getName();
String parentDir = f.getParent();
// 根目录没有上层目录
if(parentDir==null)
return false;
FTPFile[] ftpFiles = ftpClient.listFiles(parentDir);
for (int j=0; j<ftpFiles.length; j++) {
FTPFile ftpFile = ftpFiles[j];
if(ftpFile.isFile()==true && lastName.equals(ftpFile.getName())){
return true;
}
}
return false;
}
/**
* 判断路径是否为ftp目录
* @param ftpPath
* @return
* @throws IOException
*/
public boolean isDir(String ftpPath) throws IOException{
if(ftpPath==null)
return false;
File f = new File(ftpPath);
String lastName = f.getName();
String parentDir = f.getParent();
// 根目录没有上层目录
if(parentDir==null)
return true;
FTPFile[] ftpFiles = ftpClient.listFiles(parentDir);
for (int j=0; j<ftpFiles.length; j++) {
FTPFile ftpFile = ftpFiles[j];
if(ftpFile.isDirectory()==true && lastName.equals(ftpFile.getName())){
return true;
}
}
return false;
}
public boolean isDirB(String ftpPath) {
String cwd = "/";
try {
cwd = ftpClient.printWorkingDirectory();
} catch (IOException e) {
LogHelper.logger.warn("",e);
}
try {
boolean isDir = ftpClient.changeWorkingDirectory(ftpPath);
ftpClient.changeWorkingDirectory(cwd);
return isDir;
}catch (IOException e) {}
return false;
} /**
* 返回指定目录文件列表(包括子目录)
* @param ftpPath: ftp文件夹目录, 不能传文件
* @return
* @throws Exception
*/
public List<String> listFtpFiles(String ftpPath) throws Exception{
List<String> list = new ArrayList<String>();
FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath);
for (int j=0; j<ftpFiles.length; j++) {
FTPFile ftpFile = ftpFiles[j];
String subFtpPath = PathUtil.CombineUrl(ftpPath, ftpFile.getName());
if(ftpFile.isFile()==true){
list.add(subFtpPath);
}
else{
List<String> subList = listFtpFiles(subFtpPath);
list.addAll(subList);
}
}
return list;
}
/**
* 返回当前目录文件列表
* @param ftpPath
* @return
* @throws IOException
*/
public FTPFile[] listFiles(String ftpPath) throws IOException{
return ftpClient.listFiles(ftpPath);
}
/**
* ftp修改文件名
* @param from
* @param to
* @return
*/
public boolean rename(String from, String to){
boolean bl = false;
try {
bl = ftpClient.rename(from, to);
} catch (IOException e) {
LogHelper.logger.warn("",e);
}
return bl;
}
/**
* 删除文件
* @param ftpPath
* @return
*/
public boolean deleteFile(String ftpPath){
boolean bl = false;
try {
bl = ftpClient.deleteFile(ftpPath);
} catch (IOException e) {
LogHelper.logger.warn("",e);
}
return bl;
} public void test() throws Exception{
//down("/tt/ss/msgutil.zip.tmp", "/root/Desktop/tmp/", true);
down("/tt", "/root/Desktop/tmp/", false);
ftpClient.rename("from", "to");
FTPFile[] files = ftpClient.listFiles("");
for(FTPFile ff : files){
System.out.println(ff.getName());
System.out.println(ff.getLink());
}
System.out.println(files);
} // test
public static void main(String[] args) throws Exception { //FtpHelper fh = new FtpHelper("192.169.126.100",21,"yfsb","inet-eyed20");
FtpHelper fh = new FtpHelper();
boolean bl = fh.connect("172.16.9.101",21,"test1","111");
System.out.println("connect: "+bl); List<String> list = fh.listFtpFiles("/");
fh.uploadFile("C:/Users/wang/Desktop/testftp/tiedel.zip", "/tiedel.zip.tmp");
fh.deleteFile("/tiedel.zip");
bl = fh.rename("/tiedel.zip.tmp", "/tiedel.zip");
bl = fh.isFile("/33");
bl = fh.isDir("/tiedel.zip");
//fh.down("/p1/fp", "C:/Users/wang/Desktop/testftp22/tmp", false);
//fh.test();
//bl = fh.createDir("/p1/p2/p3/p4/p5");
//fh.upload("/root/Desktop/friendxml0.txt");
//fh.upload("/root/Desktop/123", "/tt/ss2/");
System.out.println(bl);
} }

Ftp上传文件的更多相关文章

  1. .net FTP上传文件

    FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...

  2. 通过cmd完成FTP上传文件操作

    一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...

  3. FTP上传文件到服务器

    一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...

  4. 再看ftp上传文件

    前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...

  5. FTP上传文件提示550错误原因分析。

    今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...

  6. FTP 上传文件

    有时候需要通过FTP同步数据文件,除了比较稳定的IDE之外,我们程序员还可以根据实际的业务需求来开发具体的工具,具体的开发过程就不细说了,这里了解一下通过C#实现FTP上传文件到指定的地址. /// ...

  7. Java ftp 上传文件和下载文件

    今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...

  8. C# FTP上传文件至服务器代码

    C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo ...

  9. Java ftp上传文件方法效率对比

    Java ftp上传文件方法效率对比 一.功能简介: txt文件采用ftp方式从windows传输到Linux系统: 二.ftp实现方法 (1)方法一:采用二进制流传输,设置缓冲区,速度快,50M的t ...

随机推荐

  1. nutch 抓取需要登录的网页

    题记:一步一坑,且行且珍惜 最近接到任务,要利用nutch去抓取公司内部系统的文章,可是需要登录才能抓到.对于一个做.net,不熟悉java,不知道hadoop,很少接触linux的我,这个过程真是艰 ...

  2. 干净地发布QT程序

    原文请看:http://www.cnblogs.com/DrizzleX/articles/2475044.html 本文研究这样一个问题:使用QT SDK和VS2008开发了一个程序,将这个程序放到 ...

  3. centos定时备份数据库超简单示例

    #mkdir -p /home/db_backup#cd /home/db_backup #vim mysql_backup.shDATE=$(date +%Y%m%d_%H%M%S) /alidat ...

  4. WebService协议

    http://www.cnblogs.com/lm3515/archive/2011/03/17/1987009.html http://blog.csdn.net/chjttony/article/ ...

  5. [Codeforces #210] Tutorial

    Link: Codeforces #210 传送门 A: 贪心,对每个值都取最大值,不会有其他解使答案变优 #include <bits/stdc++.h> using namespace ...

  6. 【筛法求素数】Codeforces Round #426 (Div. 1) A. The Meaningless Game

    先筛出来1000以内的素数. 枚举x^(1/3) 和 y^(1/3)以内的素因子,这样除完以后对于x和y剩下的因子,小的那个的平方必须等于大的. 然后判断每个素因数的次数之和是否为3的倍数,并且小的那 ...

  7. 【最大权闭合图】BZOJ1565-[NOI2009]植物大战僵尸

    害怕地发现我以前写的Dinic几乎都是有错的……??!!! [题目大意] (以下摘自popoqqq大爷)给定一个m*n的草坪,每块草坪上的植物有两个属性:1.啃掉这个植物,获得收益x(可正可负)2.保 ...

  8. [转]spring4.x注解概述

    1. 背景 注解可以减少代码的开发量,spring提供了丰富的注解功能,因项目中用到不少注解,因此下定决心,经spring4.x中涉及到的注解罗列出来,供查询使用. 2. spring注解图     ...

  9. Codeforces Gym 100269F Flight Boarding Optimization 树状数组维护dp

    Flight Boarding Optimization 题目连接: http://codeforces.com/gym/100269/attachments Description Peter is ...

  10. linux禁ping与限制ip登录

    以root进入linux系统,然后编辑文件icmp_echo_ignore_allvi /proc/sys/net/ipv4/icmp_echo_ignore_all将其值改为1后为禁止PING将其值 ...