Java实现连接FTP服务并传递文件
public class FtpClientUtil {
private String host;
private int port;
private String username;
private String password;
private int bufferSize = 10 * 1024 * 1024;
private int soTimeout = 15000;
private FTPClient ftp;
public FTPClient getFtp() {
return ftp;
}
public void setFtp(FTPClient ftp) {
this.ftp = ftp;
}
private UploadStatus uploadStatus;
public UploadStatus getUploadStatus() {
return uploadStatus;
}
public void setUploadStatus(UploadStatus uploadStatus) {
this.uploadStatus = uploadStatus;
}
public static class Builder {
private String host;
private int port = 21;
private String username;
private String password;
private int bufferSize = 1024 * 1024;
private FTPClientConfig config;
private int defaultTimeout = 15000;
private int connectTimeout = 15000;
private int dataTimeout = 15000;
private int controlKeepAliveTimeout = 300;
private int soTimeout = 15000;
public Builder() {
}
public Builder host(String host) {
this.host = host;
return this;
}
public Builder port(int port) {
this.port = port;
return this;
}
public Builder username(String username) {
this.username = username;
return this;
}
public Builder password(String password) {
this.password = password;
return this;
}
public Builder bufferSize(int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
public Builder config(FTPClientConfig config) {
this.config = config;
return this;
}
public Builder defaultTimeout(int defaultTimeout) {
this.defaultTimeout = defaultTimeout;
return this;
}
public Builder connectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
public Builder dataTimeout(int dataTimeout) {
this.dataTimeout = dataTimeout;
return this;
}
public Builder soTimeout(int soTimeout) {
this.soTimeout = soTimeout;
return this;
}
public Builder controlKeepAliveTimeout(int controlKeepAliveTimeout) {
this.controlKeepAliveTimeout = controlKeepAliveTimeout;
return this;
}
public FtpClientUtil build() throws IOException {
FtpClientUtil instance = new FtpClientUtil(this.host, this.port, this.username, this.password,
this.bufferSize, this.config, this.defaultTimeout, this.dataTimeout, this.connectTimeout,
this.controlKeepAliveTimeout, this.soTimeout);
return instance;
}
}
private FtpClientUtil(String host, int port, String username, String password, int bufferSize,
FTPClientConfig config, int defaultTimeout, int dataTimeout, int connectTimeout,
int controlKeepAliveTimeout, int soTimeout) throws IOException {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.bufferSize = bufferSize;
this.soTimeout = soTimeout;
this.ftp = new FTPClient();
if (config != null) {
this.ftp.configure(config);
}
ftp.setControlEncoding("UTF-8");
// ftp.setControlEncoding("GBK");
// ftp.setControlEncoding("gb2312");
ftp.enterLocalPassiveMode();
ftp.setDefaultTimeout(defaultTimeout);
ftp.setConnectTimeout(connectTimeout);
ftp.setDataTimeout(dataTimeout);
// ftp.setSendDataSocketBufferSize(1024 * 256);
if (this.bufferSize > 0) {
ftp.setBufferSize(this.bufferSize);
}
// keeping the control connection alive
ftp.setControlKeepAliveTimeout(controlKeepAliveTimeout);// 每大约5分钟发一次noop,防止大文件传输导致的控制连接中断
}
public FtpClientUtil connect() throws SocketException, IOException {
if (!this.ftp.isConnected()) {
this.ftp.connect(this.host, this.port);
int reply = this.ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
logger.warn("ftp服务器返回码[{}], 连接失败...", reply);
throw new IllegalStateException("连接ftp服务器失败,返回的状态码是" + reply);
}
}
this.ftp.setSoTimeout(this.soTimeout);
return this;
}
public FtpClientUtil login() throws IOException {
boolean suc = this.ftp.login(this.username, this.password);
if (!suc) {
throw new IllegalStateException("登录ftp服务器失败");
}
return this;
}
/**
* ftp上传文件功能
*
* @param file
* 要上传的文件
* @param relativePath
* 要上传到ftp服务器的相对路径
* @return
* @throws IOException
*/
public FtpClientUtil upload(File file, String relativePath) throws IOException {
FileInputStream fInputStream = new FileInputStream(file);
return this.upload(fInputStream, file.getName(), relativePath, file.length());
}
public FtpClientUtil upload(InputStream inputStream, String name, String relativePath, long localSize)
throws IOException {
ftp.setFileType(FTP.BINARY_FILE_TYPE);
changeWorkingDirectory(relativePath);
this.ftp.enterLocalPassiveMode();
FTPFile[] listFiles = this.ftp.listFiles(name);
// long localSize = inputStream.available();// ? 不知道好用否
if (listFiles.length == 1) {
long remoteSize = listFiles[0].getSize();
if (remoteSize == localSize) {
this.setUploadStatus(UploadStatus.File_Exits);
return this;
} else if (remoteSize > localSize) {
this.setUploadStatus(UploadStatus.Remote_Bigger_Local);
return this;
}
this.uploadFile(inputStream, name, remoteSize, localSize);
} else {
this.uploadFile(inputStream, name, 0, localSize);
}
logger.info("{}/{} upload success", relativePath, name);
return this;
}
private void uploadFile(InputStream inputStream, String name, long remoteSize, long localSize) throws IOException {
this.ftp.enterLocalPassiveMode();
OutputStream output = null;
long step = localSize / 100;
long process = 0;
long localreadbytes = 0L;
try {
if (remoteSize > 0) {
output = this.ftp.appendFileStream(name);
this.ftp.setRestartOffset(remoteSize);
inputStream.skip(remoteSize);
process = remoteSize / step;
localreadbytes = remoteSize;
} else {
output = this.ftp.storeFileStream(name);
}
byte[] bytes = new byte[1024];
int c;
while ((c = inputStream.read(bytes)) != -1) {
output.write(bytes, 0, c);
localreadbytes += c;
if (localreadbytes / step >= process + 10) {
process = localreadbytes / step;
logger.info("文件【" + name + "】上传ftp进度汇报, process = " + process);
}
}
logger.info("文件" + name + "上传ftp进度汇报, process = " + 100);
output.flush();
inputStream.close();
output.close();
boolean result = this.ftp.completePendingCommand();
if (remoteSize > 0) {
this.setUploadStatus(
result ? UploadStatus.Upload_From_Break_Success : UploadStatus.Upload_From_Break_Failed);
} else {
this.setUploadStatus(
result ? UploadStatus.Upload_New_File_Success : UploadStatus.Upload_New_File_Failed);
}
} catch (Exception e) {
this.setUploadStatus(
remoteSize > 0 ? UploadStatus.Upload_From_Break_Failed : UploadStatus.Upload_New_File_Failed);
}
}
public OutputStream upload(String name, String relativePath) throws IOException {
ftp.setFileType(FTP.BINARY_FILE_TYPE);
changeWorkingDirectory(relativePath);
ftp.enterLocalPassiveMode();
return this.ftp.storeFileStream(name);
}
public void changeWorkingDirectory(String relativePath) throws IOException {
if (relativePath == null) {
throw new NullPointerException("relativePath can't be null");
}
String[] dirs = relativePath.split("/");
for (String dir : dirs) {
if (!this.ftp.changeWorkingDirectory(dir)) {
if (this.ftp.makeDirectory(dir)) {
this.ftp.changeWorkingDirectory(dir);
} else {
logger.warn("{}目录创建失败, 导致不能进入合适的目录进行上传", dir);
}
}
}
}
/**
* ftp上传目录下所有文件的功能
*
* @param file
* 要上传的目录
* @param relativePath
* 要上传到ftp服务器的相对路径
* @return
* @throws IOException
*/
public FtpClientUtil uploadDir(File file, String relativePath) throws IOException {
if (!file.isDirectory()) {
throw new IllegalArgumentException("file argument is not a directory!");
}
relativePath = relativePath + "/" + file.getName();
File[] listFiles = file.listFiles();
for (File f : listFiles) {
this.uploadFree(f, relativePath);
}
return this;
}
/**
* ftp上传文件, 调用方不用区分文件是否为目录,由该方法自己区分处理
*
* @param file
* 要上传的文件
* @param relativePath
* 要上传到ftp服务器的相对路径
* @return
* @throws IOException
*/
public FtpClientUtil uploadFree(File file, String relativePath) throws IOException {
if (file.isDirectory()) {
this.uploadDir(file, relativePath);
} else {
this.upload(file, relativePath);
}
return this;
}
/**
* 本方法是上传的快捷方法,方法中自身包含了ftp 连接、登陆、上传、退出、断开各个步骤
*
* @param file
* 要上传的文件
* @param relativePath
* 要上传到ftp服务器的相对路径
*/
public boolean uploadOneStep(File file, String relativePath) {
try {
this.connect().login().uploadFree(file, relativePath);
return true;
} catch (IOException e) {
String msg = String.format("ftp上传时发生异常, filename = [%s], relativePath = [%s]", file.getName(),
relativePath);
logger.error(msg, e);
return false;
} finally {
this.disconnectFinally();
}
}
public boolean uploadOneStepForStream(InputStream inputStram, String name, String relativePath, long localSize) {
try {
this.connect().login().upload(inputStram, name, relativePath, localSize);
return true;
} catch (IOException e) {
String msg = String.format("ftp上传时发生异常, filename = [%s], relativePath = [%s]", name, relativePath);
logger.error(msg, e);
return false;
} finally {
this.disconnectFinally();
}
}
public interface OutputStreamForUpload {
public void write(OutputStream outputStream) throws IOException;
}
public boolean uploadOneStepForStream(OutputStreamForUpload outputUpload, String name, String relativePath) {
try {
this.connect().login();
OutputStream upload = this.upload(name, relativePath);
outputUpload.write(upload);
return true;
} catch (IOException e) {
String msg = String.format("ftp上传时发生异常, filename = [%s], relativePath = [%s]", name, relativePath);
logger.error(msg, e);
return false;
} finally {
this.disconnectFinally();
}
}
public FtpClientUtil logout() throws IOException {
this.ftp.logout();
return this;
}
public void disconnect() {
this.disconnectFinally();
}
private void disconnectFinally() {
if (this.ftp.isConnected()) {
try {
this.ftp.disconnect();
} catch (IOException ioe) {
logger.warn("ftp断开服务器链接异常", ioe);
}
}
}
@Override
public String toString() {
return "FtpClientHelper [host=" + host + ", port=" + port + ", username=" + username + ", password=" + password
+ "]";
}
}
看代码吧:
Java实现连接FTP服务并传递文件的更多相关文章
- PHP连接FTP服务的简单实现
PHP连接FTP服务: <?php class Ftp { private $connect; private $getback; /** * ftp连接信息 * @var array */ p ...
- ftpget 从Windows FTP服务端获取文件
/********************************************************************************* * ftpget 从Windows ...
- 通过Java WebService接口从服务端下载文件
一. 前言 本文讲述如何通过webservice接口,从服务端下载文件.报告到客户端.适用于跨系统间的文件交互,传输文件不大的情况(控制在几百M以内).对于这种情况搭建一个FTP环境,增加了系统部署的 ...
- java客户端调用ftp上传下载文件
1:java客户端上传,下载文件. package com.li.utils; import java.io.File; import java.io.FileInputStream; import ...
- C# FileStream进行FTP服务上传文件和下载文件
定义FileStream类的操作类:操作类名: FtpUpDown 上传文件 /// <summary> /// 上传文件 /// </summary> /// <par ...
- 【FTP】C# System.Net.FtpClient库连接ftp服务器(上传文件)
如果自己单枪匹马写一个连接ftp服务器代码那是相当恐怖的(socket通信),有一个评价较高的dll库可以供我们使用. 那就是System.Net.FtpClient,链接地址:https://net ...
- java 无法连接ftp服务器(500 OOPS: cannot change directory)
在使用java连接ftp服务器时可能会出现无法连接的情况,检查代码是没有错误的,这时就应该考虑一下服务器端的情况了: 首先用在本地打开命令窗口,输入:ftp ftp服务器IP,窗口会提示你输入用户名密 ...
- C# WebClient进行FTP服务上传文件和下载文件
定义WebClient使用的操作类: 操作类名称WebUpDown WebClient上传文件至Ftp服务: //// <summary> /// WebClient上传文件至Ftp服务 ...
- Java工具-检验ftp服务器的指定文件是否存在
项目工作中,需要检验ftp服务器中指定文件是否存在,在网上查阅了相关资料,可以通过ftpClient类进行实现. import org.apache.commons.net.ftp.FTP; impo ...
随机推荐
- 1-3 并发与高并发基本概念.mkv
- 关于equal和toString方法的实验报告
一 实验目的 了解equal和toString方法 二 实验软件环境 操作系统:windows xp java version: "1.7.0_51" 开发工具:Eclipse S ...
- GROUP BY ROLLUP和CUBE 用法
ROLLUP和CUBE 用法 Oracle的GROUP BY语句除了最基本的语法外,还支持ROLLUP和CUBE语句. 如果是Group by ROLLUP(A, B, C)的话 ...
- opennebula kvm日志
Fri Jul :: [InM][I]: Command execution fail: 'if [ -x "/home/oneadmin/tmp/one/im/run_probes&quo ...
- rpmbuild spec 打包jar变小了、设置禁止压缩二进制文件Disable Binary stripping in rpmbuild
Disable Binary stripping in rpmbuild 摘自:http://livecipher.blogspot.com/2012/06/disable-binary-stripp ...
- C#使用var定义变量时的四个特点
使用var定义变量时有以下四个特点: 1. 必须在定义时初始化.也就是必须是var s = “abcd”形式: 2. 一但初始化完成,就不能再给变量赋与初始化值类型不同的值了. 3. var要求是 ...
- javascript总结2: Date对象
1 Date 对象 Date 对象用于处理日期与时间. Date()的方法很多,这里只总结工作必备的方法! 2 常用方法 创建个 Date 对象:const mydate=new Date(); &l ...
- HDU 4430 Yukari's Birthday (二分)
题意:有 n 个蜡烛,让你插到蛋糕上,每一层要插 k^i个根,第0层可插可不插,插的层数是r,让 r * k 尽量小,再让 r 尽量小,求r 和 k. 析:首先先列出方程来,一个是不插的一个是插的,比 ...
- 图的遍历——BFS
原创 裸一篇图的BFS遍历,直接来图: 简单介绍一下BFS遍历的过程: 以上图为例子,从0开始遍历,访问0,按大小顺序访问与0相邻的所有顶点,即先访问1,再访问2: 至此顶点0已经没有作用了,因为其本 ...
- go-spew golang最强大的调试助手,没有之一
go内置的fmt.sprintf已经很强大了,但是和spew比起来还是相形见绌,这里来一个例子. import ( "fmt" "github.com/davecgh/g ...