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 ...
随机推荐
- SpringMVC一些功能
1.日期格式转换 当页面提交日期格式时 默认的格式为2017/10/1 如果指定日期格式为2017-10-1 //初始化绑定日期格式--不定义初始化格式时只能默认用yyyy/MM/dd格式 @Init ...
- avaScript技术面试时要小心的三个问题
JavaScript是所有现代浏览器的官方语言.同样的,JavaScript面试题出现在各种各样的面试中. 这篇文章不是讲述JavaScript最新的库.日常的开发实践,或是ES6的新功能.当然了,上 ...
- Bootstrap 实现CRUD示例及代码
https://github.com/wenzhixin/bootstrap-table-examples/blob/master/crud/index.html <!DOCTYPE html& ...
- [thinkphp] 隐藏后台地址
转自 http://document.thinkphp.cn/manual_3_2.html#module_deploy 如果不希望用户直接访问某个模块,可以设置模块映射(对后台的保护会比较实用). ...
- java 中整数类型的进制转换
int a=10; Integer.toBinaryString(a); //转换成2进制Integer.toOctalString(a); //转换成8进制Integer.toHexString( ...
- Java实现蛇形矩阵
public class Solution { //下x++ 左y-- 上x-- 右y++ public void prints(int n) { int[][] mp = new int[n][n] ...
- 洛谷——P1869 愚蠢的组合数
P1869 愚蠢的组合数 题目描述 最近老师教了狗狗怎么算组合数,狗狗又想到了一个问题... 狗狗定义C(N,K)表示从N个元素中不重复地选取K个元素的方案数. 狗狗想知道的是C(N,K)的奇偶性. ...
- [BZOJ3990][SDOI2015]排序(DFS)
3990: [SDOI2015]排序 Time Limit: 20 Sec Memory Limit: 128 MBSubmit: 902 Solved: 463[Submit][Status][ ...
- BZOJ 4059 [Cerc2012]Non-boring sequences(启发式分治)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=4059 [题目大意] 一个序列被称为是不无聊的,仅当它的每个连续子序列存在一个独一无二的 ...
- 【贪心】【后缀自动机】XIII Open Championship of Y.Kupala Grodno SU Grodno, Saturday, April 29, 2017 Problem E. Enter the Word
题意:给你一个串,让你从左到右构造这个串,一次操作可以直接在当前串后面添加一个任意字符,或者拷贝当前串的任意一个子串到当前串的后面.问你最少要多少次操作才能构造出这个串. 从前向后贪心,从当前已构造的 ...