java操作FTP的一些工具方法
java操作FTP还是很方便的,有多种开源支持,这里在apache开源的基础上自己进行了一些设计,使用起来更顺手和快捷。
思路:
1.设计FTPHandler接口,可以对ftp,sftp进行统一操作,比如上传,下载,删除,获取关闭连接等
2.对FTP和SFTP的实现
3.设计一个工厂(考虑以后可能有sftp,ftp两种,目前只实现一种FTP的),用来生成FTPHandler
4.简单使用说明
作为码农,上代码更实在。
接口 FTPHandler.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException; import org.apache.commons.net.ftp.FTPClient; public interface FTPHandler {
/**
* 获取连接
* @return
* @throws SocketException
* @throws IOException
*/
public boolean connect() throws SocketException, IOException;
/**
* 上传文件
* @param remotePath 要保存到的远程ftp目录
* @param originalFilename 要保存为远程ftp文件名
* @param is 输入流
* @return
*/
public boolean uploadFile(String remotePath,String originalFilename, InputStream is); /**
* 下载文件
* @param remotePath 文件所在的远程ftp目录
* @param filename 文件名
* @param os 输出流
* @return
* @throws IOException
*/
public boolean downFile(String remotePath,String filename, OutputStream os) throws IOException; /**
* 删除文件
* @param remotePath 文件所在ftp目录
* @param filename 文件名
* @return
* @throws IOException
*/
boolean deleteFiles(String remotePath,String filename) throws IOException; /**
* 关闭客户端
* @param ftpClient
*/
public void closeClient(FTPClient ftpClient); }
实现类 FTPHandlerImpl.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.Properties; import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class FTPHandlerImpl implements FTPHandler { private static final Logger LOGGER= LoggerFactory.getLogger(FTPHandlerImpl.class); private static String url="";
private static int port=21;
private static String username=null;
private static String password=null;
private static String remotePath=null;
private FTPClient ftpClient = null; static {
Properties configP;
try {
configP = PropertiesUtils.getWebLoProperties("configure");
url = configP.getProperty("downFileService.ftp.url");
username = configP.getProperty("downFileService.ftp.username");
password = configP.getProperty("downFileService.ftp.password");
remotePath = configP.getProperty("downFileService.ftp.remotePath");
// localPath = configP.getProperty("downFileService.ftp.localPath");
} catch (Exception e) {
e.printStackTrace();
}
} public FTPHandlerImpl() {
FTPClient ftpClient = new FTPClient();
this.ftpClient=ftpClient;
} @Override
public boolean connect() throws SocketException, IOException {
boolean success=true;
ftpClient.connect(url, port);
boolean login = ftpClient.login(username, password);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
success=false;
}
return success&&login; } @Override
public boolean uploadFile(String _remotePath,String storeFilename, InputStream is) {
boolean success=false;
try {
// 切换到path指定的目录
if(StringUtils.isBlank(_remotePath)){
_remotePath=remotePath;
} createOrChangeDir(_remotePath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
success = ftpClient.storeFile(storeFilename, is);
is.close();
} catch (IOException e) {
e.printStackTrace(); }
closeClient(ftpClient);
return success;
} @Override
public boolean downFile(String _remotePath,String filename, OutputStream os) throws IOException {
// 解决图片上传失真
//解决图片下载失真
// 切换到path指定的目录
if(StringUtils.isBlank(_remotePath)){
_remotePath=remotePath;
}
createOrChangeDir(_remotePath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
FTPFile[] ftpFiles = ftpClient.listFiles();
boolean success=false;
for (FTPFile file : ftpFiles) {
if (file.getName().equals(filename)) {
filename = file.getName();
success = ftpClient.retrieveFile(filename, os);
break;
}
}
closeClient(ftpClient);
return success;
} @Override
public boolean deleteFiles(String _remotePath,String fileName) throws IOException {
// 切换到path指定的目录
if(StringUtils.isBlank(_remotePath)){
_remotePath=remotePath;
}
ftpClient.changeWorkingDirectory(_remotePath);
FTPFile[] ftpFiles = ftpClient.listFiles();
boolean isDelete = false;
for (FTPFile file : ftpFiles) {
if (fileName.equalsIgnoreCase(file.getName())) {
ftpClient.deleteFile(file.getName());
isDelete = true;
} }
closeClient(ftpClient);
return isDelete;
} @Override
public void closeClient(FTPClient ftpClient) {
try {
if (ftpClient != null) {
ftpClient.logout();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} } /**
* 创建目录(有则切换目录,没有则创建目录)
* @param dir
* @return
*/
private boolean createOrChangeDir(String dir){
if(StringUtils.isBlank(dir))
return true;
String d;
try {
//目录编码,解决中文路径问题
d = new String(dir.toString().getBytes("UTF-8"),"iso-8859-1");
//尝试切入目录
if(ftpClient.changeWorkingDirectory(d))
return true; dir = StringUtils.removeStart(dir, "/");
dir = StringUtils.removeEnd(dir, "/");
String[] arr = dir.split("/");
StringBuffer sbfDir=new StringBuffer();
//循环生成子目录
for(String s : arr){
sbfDir.append("/");
sbfDir.append(s);
//目录编码,解决中文路径问题
d = new String(sbfDir.toString().getBytes("UTF-8"),"iso-8859-1");
//尝试切入目录
if(ftpClient.changeWorkingDirectory(d))
continue;
if(!ftpClient.makeDirectory(d)){
LOGGER.info("[失败]ftp创建目录:"+sbfDir.toString());
return false;
}
LOGGER.info("[成功]创建ftp目录:"+sbfDir.toString());
}
//将目录切换至指定路径
return ftpClient.changeWorkingDirectory(d);
} catch (Exception e) {
e.printStackTrace();
return false;
}
} }
工场类 FTPFactory.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
public class FTPFactory { public static final String HANDLE_FTP="ftp";
public static final String HANDLE_SFTP="sftp"; /**
* 获取FTPHandler对象,目前只实现了ftp
* @param handleName HANDLE_FTP或HANDLE_SFTP
* @return
*/
public static FTPHandler getHandler(String handleName){
FTPHandler handler=null;
if(handleName.equals(HANDLE_FTP)){
handler=new FTPHandlerImpl();
}
return handler;
} public static void main(String[] args) throws SocketException, IOException {
FTPHandler handler = getHandler(HANDLE_FTP);
boolean connect = handler.connect();
if(connect){
File f=new File("C:\\Users\\pcdalao\\Desktop\\definitions.json");
InputStream is=new FileInputStream(f);
boolean uploadFile = handler.uploadFile("/upload_case/20170825/测试", "definition_test.json", is);
if(uploadFile){
System.out.println("success");
}else{ System.out.println("fail");
} } } }
使用的时候,直接从工程获取即可。
说明:PropertiesUtils这个工具类,有很多可以替代的实现,需要自己实现哦。
就此一个完整的FTP操作完成。记录一下,方便自己,也方便园子里的朋友参考。设计不当之处,请多多指教。
java操作FTP的一些工具方法的更多相关文章
- JQuery操作类数组的工具方法
JQuery学习之操作类数组的工具方法 在很多时候,JQuery的$()函数都返回一个类似数据的JQuery对象,例如$('div')将返回div里面的所有div元素包装的JQuery对象.在这中情况 ...
- Java操作文件夹的工具类
Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...
- Java操作FTP工具类(实例详解)
这里使用Apache的FTP jar 包 没有使用Java自带的FTPjar包 工具类 package com.zit.ftp; import java.io.File; import java.i ...
- java 操作FTP
package comm.ftp; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInput ...
- Java 操作Redis封装RedisTemplate工具类
package com.example.redisdistlock.util; import org.springframework.beans.factory.annotation.Autowire ...
- Java操作XML的JAXB工具
在java中操作XML的工作中中,比较方便的工具是JAXB(Java Architecture for XML Binding). 利用这个工具很方便生成XML的tag和Java类的对应关系.参照网上 ...
- Java操作属性文件之工具类
最近空闲时间整理一下平时常用的一下工具类,重复造轮子实在是浪费时间,如果不正确或者有待改善的地方,欢迎指教... package com.hsuchan.business.utils; import ...
- java后台获取Access_token的工具方法
本方法主要通过java后台控制来获取Access_token,需要你已经知道自己的ID跟密码 因为微信的权限设置大概每天可以获取两千条,每条有效时间为2小时 /** * 输入自己的id跟密码,获取微信 ...
- java操作FTP,实现文件上传下载删除操作
上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端 ...
随机推荐
- CentOS 6.8下网卡配置、桥接模式和NAT连接模式、VMware虚拟机克隆网卡配置
模式一:桥接模式: 1. 在VMware中安装好虚拟机后,虚拟机网卡设置:选择桥接模式 2. 查看本机的网络信息: 找到ip.子网掩码.网关.DNS等. 找一个没有使用的ip,例如:192.168.1 ...
- 《Orange‘s》Loader
Loader 作用 引导扇区只有512个字节,能做的事情很少,局限性太大.所以需要一个程序,通过引导扇区加载入内存,然后将控制权交给它,这样就突破了512字节的限制.这个程序便是loader. 加载过 ...
- FileInputStream文件字节输入流程序
第一种:.read() 一次读一个字节,返回值类型是int,方法读取硬盘访问次数太频繁.缺点:效率低,伤硬盘 import java.io.FileInputStream; import java.i ...
- webpack优化以及node版本
最近做的这个项目webpack用的是1.X的版本,真的非常多的坑,然后最近在疯狂的做优化: 事情的起因是每次我npm run dev的时侯都需要5分钟+,这个速度真的是难以忍受,然后就尝试去做项目的优 ...
- 【1天】黑马程序员27天视频学习笔记【Day02】
02.01常量的概述和使用 * A:什么是常量 * 在程序执行的过程中其值不可以发生改变 * B:Java中常量的分类 * 字面值常量 * 自定义常量(面向对象部分讲) * C:字面 ...
- ./configure -build,-host,-target设置
build:执行代码编译的主机,正常的话就是你的主机系统.这个参数一般由config.guess来猜就可以.当然自己指定也可以.host:编译出来的二进制程序所执行的主机,因为绝大多数是如果本机编译, ...
- byte -> int
传送门 传送门2 以下copy: int i = 0; i += ((b[0] & 0xff) << 24); i += ((b[1] & 0xff) <&l ...
- 坑 flutter Positioned相关
child: new Positioned( right: 0.0, ...... 报错: Positioned widgets must be placed directly inside Stac ...
- 【LeetCode刷题系列 - 003题】Longest Substring Without Repeating Characters
题目: Given a string, find the length of the longest substring without repeating characters. Example 1 ...
- iOS多图上传
iOS多图上传涉及到多线程问题,个人比较喜欢使用GCD操作,下边是最近写的一个多图上传代码,附带相关注释 __block BOOL allSucc = YES; __block int m = 0; ...