Ftp上传文件
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上传文件的更多相关文章
- .net FTP上传文件
FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...
- 通过cmd完成FTP上传文件操作
一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...
- FTP上传文件到服务器
一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...
- 再看ftp上传文件
前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...
- FTP上传文件提示550错误原因分析。
今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...
- FTP 上传文件
有时候需要通过FTP同步数据文件,除了比较稳定的IDE之外,我们程序员还可以根据实际的业务需求来开发具体的工具,具体的开发过程就不细说了,这里了解一下通过C#实现FTP上传文件到指定的地址. /// ...
- Java ftp 上传文件和下载文件
今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...
- C# FTP上传文件至服务器代码
C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo ...
- Java ftp上传文件方法效率对比
Java ftp上传文件方法效率对比 一.功能简介: txt文件采用ftp方式从windows传输到Linux系统: 二.ftp实现方法 (1)方法一:采用二进制流传输,设置缓冲区,速度快,50M的t ...
随机推荐
- 调用git命令行执行更新的思路
cd /usr/local/software/CloudPlatformUtil/GitLab # CentOS6.5自带的git版本是1.7.1 # 安装高版本git wget -O git.zip ...
- Go语言入门之变量声明
1.使用var关键字声明变量,如果没有初始化,则变量默认为零值. var a string "hello world" 2.根据值自行判定变量类型 3.多变量声明 ,, 4.使用v ...
- Spark streaming技术内幕6 : Job动态生成原理与源码解析
原创文章,转载请注明:转载自 周岳飞博客(http://www.cnblogs.com/zhouyf/) Spark streaming 程序的运行过程是将DStream的操作转化成RDD的操作,S ...
- hdu 1556 Color the ball(线段树区间维护+单点求值)
传送门:Color the ball Color the ball Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/3276 ...
- POJ 2031 Building a Space Station【最小生成树+简单计算几何】
You are a member of the space station engineering team, and are assigned a task in the construction ...
- struts2核心配置之Result
result作用:在struts.xml中,使用<result>元素配置result逻辑视图和物理视图之间的映射 元素属性 属性 说明 是否必须 name 指定逻辑视图的名称(Action ...
- java Integer parseInt()
先来一段代码,代码很简单的,如下: public static void main(String[] args) { Integer a = Integer.parseInt("3" ...
- python队列、线程、进程、协程(转)
原文地址: http://www.cnblogs.com/wangqiaomei/p/5682669.html 一.queue 二.线程 #基本使用 #线程锁 #自定义线程池 #生产者消费者模型(队列 ...
- 树形dp(poj 1947 Rebuilding Roads )
题意: 有n个点组成一棵树,问至少要删除多少条边才能获得一棵有p个结点的子树? 思路: 设dp[i][k]为以i为根,生成节点数为k的子树,所需剪掉的边数. dp[i][1] = total(i.so ...
- JZYZOJ1383 [usaco2003feb]impster 位运算 最短路
http://172.20.6.3/Problem_Show.asp?id=1383 找能到达某个状态的最小操作数,然后把所有状态扫一遍即可,要额外判定一下起始就有的状态(如果起始里没有0那么这些状 ...