package cn.ftp.util;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
/**
* ftp工具类
* @author lijj
*/
public class FtpUtil {
private final static Log logger = LogFactory.getLog(FtpUtil.class);
/**
* 获取FTPClient对象
*
* @param ftpHost
* FTP主机服务器
*
* @param ftpPassword
* FTP 登录密码
*
* @param ftpUserName
* FTP登录用户名
*
* @param ftpPort
* FTP端口 默认为21
*
* @return
*/
public static FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
FTPClient ftpClient = null;
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) {
e.printStackTrace();
logger.info("FTP的IP地址可能错误,请正确配置。");
} catch (IOException e) {
e.printStackTrace();
logger.info("FTP的端口错误,请正确配置。");
}
return ftpClient;
}
/**
* 从FTP服务器下载文件
*
* @param ftpHost FTP IP地址
*
* @param ftpUserName FTP 用户名
*
* @param ftpPassword FTP用户名密码
*
* @param ftpPort FTP端口
*
* @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
*
* @param localPath 下载到本地的位置 格式:H:/download
*
* @param fileName 文件名称
*/
public static void downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort,
String ftpPath, String localPath, String fileName) {
FTPClient ftpClient = null;
try {
ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);
InputStream retrieveFileStream = ftpClient.retrieveFileStream(fileName);
// 第一种方式下载文件(推荐)
/*
* File localFile = new File(localPath + File.separatorChar +
* fileName); OutputStream os = new FileOutputStream(localFile);
* ftpClient.retrieveFile(fileName, os); os.close();
*/
// 第二种方式下载:将输入流转成字节,再生成文件,这种方式方便将字节数组直接返回给前台jsp页面
byte[] input2byte = input2byte(retrieveFileStream);
byte2File(input2byte, localPath, fileName);
if(null != retrieveFileStream){
retrieveFileStream.close();
}
} catch (FileNotFoundException e) {
logger.error("没有找到" + ftpPath + "文件");
e.printStackTrace();
} catch (SocketException e) {
logger.error("连接FTP失败.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
logger.error("文件读取错误。");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
//退出登录
ftpClient.logout();
//关闭连接
ftpClient.disconnect();
} catch (IOException e) {
}
}
}
}
/**
* Description: 向FTP服务器上传文件
*
* @param host
* FTP服务器hostname
* @param port
* FTP服务器端口
* @param username
* FTP登录账号
* @param password
* FTP登录密码
* @param basePath
* FTP服务器基础目录
* @param filePath
* FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
* @param filename
* 上传到FTP服务器上的文件名
* @param input
* 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword,
String basePath, String filePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftpClient = null;
try {
int reply;
ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return result;
}
// 切换到上传目录
if (!ftpClient.changeWorkingDirectory(basePath + filePath)) {
// 如果目录不存在创建目录
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir))
continue;
tempPath += "/" + dir;
if (!ftpClient.changeWorkingDirectory(tempPath)) {
if (!ftpClient.makeDirectory(tempPath)) {
return result;
} else {
ftpClient.changeWorkingDirectory(tempPath);
}
}
}
}
// 设置上传文件的类型为二进制类型
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setControlEncoding("UTF-8");
// 上传文件
if (!ftpClient.storeFile(filename, input)) {
return result;
}
if(null != input){
input.close();
}
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
//退出登录
ftpClient.logout();
//关闭连接
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
/**
* 删除文件 未测试
*
* @param hostname
* FTP服务器地址
* @param port
* FTP服务器端口号
* @param username
* FTP登录帐号
* @param password
* FTP登录密码
* @param pathname
* FTP服务器保存目录
* @param filename
* 要删除的文件名称
* @return
*/
public static boolean deleteFile(String hostname, int port, String username, String password, String pathname,
String filename) {
boolean flag = false;
FTPClient ftpClient = new FTPClient();
try {
// 连接FTP服务器
ftpClient.connect(hostname, port);
// 登录FTP服务器
ftpClient.login(username, password);
// 验证FTP服务器是否登录成功
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
return flag;
}
// 切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
ftpClient.dele(filename);
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
//退出登录
ftpClient.logout();
//关闭连接
ftpClient.disconnect();
} catch (IOException e) {
}
}
}
return flag;
}
// 将字节数组转换为输入流
public static final InputStream byte2Input(byte[] buf) {
return new ByteArrayInputStream(buf);
}
// 将输入流转为byte[]
public static final byte[] input2byte(InputStream inStream) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
// 将byte[]转为文件
public static void byte2File(byte[] buf, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {
dir.mkdirs();
}
file = new File(filePath + File.separat
JAVA实现ftp客户端的上传、下载、删除
4星 · 超过85%的资源 需积分: 46 41 浏览量
2018-01-04
10:26:08
上传
评论 6
收藏 529KB ZIP 举报
飞奔的蜗牛2017
- 粉丝: 79
- 资源: 16
最新资源
- Sunfounder智能视频车载套件,适用于Raspberry Pi-智能车
- 计算机二级考试的一些编程题(大学生专用 )-计算机二级
- 2019年之江杯人工智能大赛电商评论观点挖掘赛道TOP3-电赛
- 基于PCA和SVM的人脸识别
- Python 爬虫爬取 Instagram 博主照片视频-Python 爬虫
- dot-font字体库
- 实现各种面向对象设计模式的C + +项目集合-Object-C
- 硬件设计基础:数字电压表;51单片机蓝牙通信+Proteus 仿真
- 用于使用JavaScript制作Scratch类项目的库-Scratch
- 2005-2022年全国及31省绿色信贷水平原始数据及测算(含原始数据+计算过程+计算结果).xls
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈