1.pom文件中添加依赖

<!-- ftp使用 -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency> 2.代码样例:
package com.migu.reading.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply; import com.migu.reading.iufs.domain.InviteResultCode;
import com.migu.reading.iufs.domain.IufsException; import java.io.*;
import java.net.SocketException; public class FtpUtil
{ private static final Log LOGGER = LogFactory.getLog(FtpUtil.class); /**
* 获取FTPClient对象
*
* @param ftpHost
* FTP主机服务器
* @param ftpPassword
* FTP 登录密码
* @param ftpUserName
* FTP登录用户名
* @param ftpPort
* FTP端口 默认为21
* @return
* @throws IOException
* @throws Exception
*/
public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort)
{
FTPClient ftpClient = new FTPClient();
try
{
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
{
LOGGER.info("未连接到FTP,用户名或密码错误。");
ftpClient.disconnect();
}
else
{
LOGGER.info("FTP连接成功。");
}
}
catch (SocketException e)
{
LOGGER.error("FTP的IP地址可能错误,请正确配置。e:{}" + e);
}
catch (IOException e)
{
LOGGER.error("FTP的端口错误,请正确配置。e:{}" + e);
}
return ftpClient;
} /**
* 下载文件
*
* @param ftpHost ftp服务器地址
* @param ftpUserName 用户名
* @param ftpPassword 指定用户密码
* @param ftpPort ftp服务器端口号
* @param ftpPath ftp文件存放物理路径
* @param localPath 下载到的本地路径
*/
public static boolean downloadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort,
String ftpPath, String localPath)
{
FTPClient ftpClient = null;
boolean result = false;
boolean createOrExistsDir = FileTools.createOrExistsDir(localPath);
if (!createOrExistsDir)
{
LOGGER.error("FtpUtil.downloadFile create localPath error");
return result;
}
try
{
ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
// 设置被动模式,开通一个端口来传输数据
ftpClient.enterLocalPassiveMode();
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setBufferSize(500);
// 截取路径
String path = ftpPath.substring(0, ftpPath.lastIndexOf("/") + 1);
boolean changeWorkingDirectory =
ftpClient.changeWorkingDirectory(new String(path.getBytes(), "ISO-8859-1")); if (changeWorkingDirectory)
{
File ftpPathFile = new File(ftpPath);
File localFile = new File(localPath + "/" + ftpPathFile.getName()); FileOutputStream os = new FileOutputStream(localFile);
String ftpPathFileName = new String(ftpPathFile.getName().getBytes("UTF-8"), "ISO-8859-1");
result = ftpClient.retrieveFile(ftpPathFileName, os);
os.close();
ftpClient.logout();
}
else
{
LOGGER.error("FtpUtil.downloadFile ftpPath is error");
throw new IufsException(InviteResultCode.FTP_PATH_ERROR.getCode(),
InviteResultCode.FTP_PATH_ERROR.getDesc());
}
// ftpClient.listDirectories()
// 判断文件是否存在
// String file = ftpPath.substring(ftpPath.lastIndexOf("/") + 1);
// //
// InputStream is =
// ftpClient.retrieveFileStream(new String(file.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
// if (is == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE)
// {
// throw new IufsException(InviteResultCode.FTP_PATH_ERROR.getCode(),
// InviteResultCode.FTP_PATH_ERROR.getDesc());
// }
// is.close();
// ftpClient.completePendingCommand(); return result;
}
catch (FileNotFoundException e)
{
LOGGER.error("没有找到" + ftpPath + "文件,e:{}", e);
return false;
}
catch (SocketException e)
{
LOGGER.error("连接FTP失败.e:{}", e);
return false;
}
catch (IOException e)
{
LOGGER.error("文件读取错误。e:{}", e);
return false;
}
} /**
* 上传文件
*
* @param ftpHost ftp服务器地址
* @param ftpUserName anonymous匿名用户登录,不需要密码。administrator指定用户登录
* @param ftpPassword 指定用户密码
* @param ftpPort ftp服务员器端口号
* @param ftpPath ftp文件存放物理路径
* @param fileName 文件路径 */
public static void uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath,
String fileName, InputStream input)
{
FTPClient ftp = null;
try
{
ftp = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
ftp.changeWorkingDirectory(ftpPath);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
boolean storeFile = ftp.storeFile(fileName, input);
System.out.println("是否上传成功--" + storeFile);
input.close();
ftp.logout();
System.out.println("upload succes!");
}
catch (Exception e)
{
e.printStackTrace();
}
} @SuppressWarnings("unused")
private static boolean downFileOrDir(String ftpFilePath, String localDir, String ftpHost, String ftpUserName,
String ftpPassword, int ftpPort)
{ boolean result = true; FileOutputStream fos = null;
FTPClient ftpClient = null;
try
{
ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); File file = new File(ftpFilePath);
File temp = new File(localDir);
ftpClient.enterLocalPassiveMode();
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); if (!temp.exists())
{
if (!temp.mkdirs())
{
}
}
// 如果不是目录则表示是单个文件的下载
String filePathsss = ftpFilePath.substring(0, ftpFilePath.lastIndexOf("/") + 1);
boolean b = ftpClient.changeWorkingDirectory(filePathsss);
if (!b)
{
LOGGER.error("------------ftpFile not exists-------------");
// 报错
}
String[] names = ftpClient.listNames();
for (String name : names)
{
if (file.getName().equals(name))
{
File localfile = new File(localDir + File.separator + file.getName());
if (!localfile.exists())
{
fos = new FileOutputStream(localfile);
result = ftpClient.retrieveFile(file.getName(), fos);
}
else
{
if (!localfile.delete())
{
}
fos = new FileOutputStream(localfile);
result = ftpClient.retrieveFile(file.getName(), fos);
}
ftpClient.changeToParentDirectory();
return result;
}
}
}
catch (IOException e)
{
try
{
if (null != fos)
{
fos.close();
}
}
catch (IOException e1)
{
}
result = false;
}
catch (Exception e)
{
result = false;
}
finally
{
try
{
if (null != fos)
{
fos.close();
}
}
catch (IOException e)
{
}
}
return result;
} public static void main(String[] args)
{
/*****下载文件*********/
// boolean downloadFile = downloadFile("10.211.93.173",
// "commonservice",
// "1qaz@WSX",
// 21,
// "/home/commonservice/data/vcode/muban.zip",
// "D://file");
// System.out.println("是否下载成功===》" + downloadFile); // boolean downloadFile = downFileOrDir("/home/commonservice/data/vcode/vcodeTemplate20190402162646.zip",
// "D://file",
// "10.211.93.173",
// "commonservice",
// "1qaz@WSX",
// 21);
// System.out.println(downloadFile);
// "ftp://10.211.93.173/aa.zip"
// "ftp://10.211.93.173/copyrights_exportFile/Copyrights_20171101164204.zip",
// boolean downloadFile =
// downFileOrDir("ftp://10.211.93.173/aa.zip", "D://file", "10.211.93.173", "commonservice", "1qaz@WSX", 21);
// System.out.println(downloadFile); /********上传******************/
// String filePath = "D:\\file";
// String fileName = "muban.zip";
// FileInputStream input = null;
// try
// {
// input = new FileInputStream(new File(filePath + File.separatorChar + fileName));
// }
// catch (FileNotFoundException e)
// {
// e.printStackTrace();
// }
// uploadFile("10.211.93.173",
// "commonservice",
// "1qaz@WSX",
// 21,
// "/home/commonservice/data/vcode/",
// fileName,
// input);
}
}

ftp使用的更多相关文章

  1. 8.仿阿里云虚拟云服务器的FTP(包括FTP文件夹大小限制)

    平台之大势何人能挡? 带着你的Net飞奔吧!:http://www.cnblogs.com/dunitian/p/4822808.html#iis 原文:http://dnt.dkill.net/Ar ...

  2. Hyper-V无法文件拖拽解决方案~~~这次用一个取巧的方法架设一个FTP来访问某个磁盘,并方便的读写文件

    异常处理汇总-服 务 器 http://www.cnblogs.com/dunitian/p/4522983.html 服务器相关的知识点:http://www.cnblogs.com/dunitia ...

  3. 阿里云学生优惠Windows Server 2012 R2安装IIS,ftp等组件,绑定服务器域名,域名解析到服务器,域名备案,以及安装期间错误的解决方案

     前言: 这几天终于还是按耐不住买了一个月阿里云的学生优惠.只要是学生,在学信网上注册过,并且支付宝实名认证,就可以用9块9的价格买阿里云的云服务ECS.确实是相当的优惠. 我买的是Windows S ...

  4. win7下利用ftp实现华为路由器的上传和下载

    win7下利用ftp实现华为路由器的上传和下载 1.  Win7下ftp的安装和配置 (1)开始->控制面板->程序->程序和功能->打开或关闭Windows功能 (2)在Wi ...

  5. Java实现FTP文件与文件夹的上传和下载

    Java实现FTP文件与文件夹的上传和下载 FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制 ...

  6. centos下开启ftp服务

    如果要ftp访问linux需要安装ftp服务,vsftpd是Linux下比较好的的FTP服务器. 一.检查安装vsftp //检查是否安装vsftpd rpm -qa | grep vsftpd // ...

  7. 解决开启服务器防火墙导致ftp不能连接的问题

    在防火墙设置的"高级"选项卡中的"网络连接设置"--"本地连接"--"设置"中添加了"FTP服务器" ...

  8. centos6.5 nginx-1.8.0和ftp搭建图片服务器

    一.Nginx的安装步骤 1.Nginx安装环境: gcc: 安装nginx需要先将官网下载的源码进行编译,编译依赖gcc环境,如果没有gcc环境,需要安装gcc:yum install gcc-c+ ...

  9. Jenkins配置MSBuild实现自动部署(MSBuild+SVN/Subversion+FTP+BAT)

    所要用到的主要插件: [MSBuild Plugin] 具体操作: 1.配置MSBuild的版本 [系统管理]->[Global Tool Configuration]->[MSBuild ...

  10. [CentOs7]搭建ftp服务器(2)——添加用户

    摘要 上篇文章完成了ftp服务器的安装与匿名访问的内容,当然出于安全的考虑是不允许匿名访问服务器的,所以就有了本篇的内容 ,为ftp服务器添加用户,用改用户进行访问. vsftpd添加用户 FTP用户 ...

随机推荐

  1. 【转】socket通信-C#实现udp通讯

    在日常碰到的项目中,有些场景下不适合使用tcp常连接,而需要靠UDP无连接的数据收发.那么如何使用SharpSocket完成UDP收发数据呢?其中要掌握的关键点是什么呢? 点击查看原博文内容

  2. ASP.NET Core 配置文件

    在ASP.NET Core 中,应用程序配置数据可以使用JSON, XML 和 INI格式 和内置环境变量,命令行参数或内存中的集合. 1.如何获取和设置配置 ASP.NET Core配置系统针对以前 ...

  3. Java自学-数字与字符串 字符串转换

    Java中把数字转换为字符串,字符串转换为数字 步骤 1 : 数字转字符串 方法1: 使用String类的静态方法valueOf 方法2: 先把基本类型装箱为对象,然后调用对象的toString pa ...

  4. 时间格式在ios和安卓兼容性的问题:

    在做项目时,在时间显示上遇到一个问题,取后台返回的时间时,在ios手机上时间不显示,安卓手机正常,最后通过Vconsole工具发现,ios不能支持用“—”分割的时间,此外后台返回的时间格式为x年x月x ...

  5. [摘抄] 3.AMD规范与CommonJS规范的兼容性

    3. AMD规范与CommonJS规范的兼容性 CommonJS规范加载模块是同步的,也就是说,只有加载完成,才能执行后面的操作. AMD规范则是非同步加载模块,允许指定回调函数. 由于Node.js ...

  6. 如何显示IntelliJ IDEA工具的Run Dashboard功能(转)

    从 JetBrains released IntelliJ IDEA 2017.2.1 版本之后,新出的功能‘Run Dashboard,它能非常方便的提供开发人员查看本地springboot服务运行 ...

  7. 《JavaScript高级程序设计》笔记:附录A ECMAScript Harmony

    一般性变化 常量 用const关键字声明常量,声明的变量在初始赋值后,就不能进行修改了,如下代码: const MAX_SIZE = 25; MAX_SIZE = 10; //报错 块级作用域及其他作 ...

  8. FreePascal - CodeTyphon 如何让编译的程序更小!

    CodeTyphon 6.9 在菜单[project]-->[project option]的弹出界面中 选择[compiler option]-->[debugging] 1,去掉“Ge ...

  9. 【漏洞复现】Apache Solr via Velocity template远程代码执行

    0x01 概述 Solr简介 Apache Solr 是一个开源的企业级搜索服务器.Solr 使用 Java 语言开发,主要基于 HTTP 和 Apache Lucene 实现.Apache Solr ...

  10. Shell 编程 条件语句

    本篇主要写一些shell脚本条件语句的使用. 条件测试 test 条件表达式 [ 条件表达式 ] 文件测试 -d:测试是否为目录(Directory). -e:测试文件或目录是否存在(Exist). ...