您的位置:首页 > 运维架构 > Apache

基于apache的commons-net-3.3.jar的 ftp java代码上传下载文件

2016-08-24 11:14 766 查看
package com.mnt.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
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;
import org.springframework.util.StringUtils;

/**
* FTP服务器工具
* 注意:执行顺序
* 1、先连接FTP服务器
* 2、设置上传/下载目录
* 3、执行其它
*
* @author zcq
* @version 1.0
*
*          变更履历:
*          v1.0 2016-7-29 zcq 初版
*/
public class FtpUtil {

public static final Logger LOGGER = LoggerFactory.getLogger(FtpUtil.class);

public static final String ANONYMOUS_LOGIN = "anonymous";

private FTPClient ftp;

private boolean is_connected;

public FtpUtil() {
ftp = new FTPClient();
is_connected = false;

ftp.setDefaultTimeout(7200);
ftp.setConnectTimeout(7200);
ftp.setDataTimeout(7200);
}

public FtpUtil(int defaultTimeoutSecond, int connectTimeoutSecond, int dataTimeoutSecond) {
ftp = new FTPClient();
is_connected = false;

ftp.setDefaultTimeout(defaultTimeoutSecond);
ftp.setConnectTimeout(connectTimeoutSecond);
ftp.setDataTimeout(dataTimeoutSecond);
}

/**
* 连接FTP服务器
*
* @author zcq
* @param host
* @param port
* @param user
* @param password
* @param isTextMode
* @throws IOException
*/
public void connect(String host, int port, String user, String password, boolean isTextMode) throws IOException {
// 连接FTP服务器
try {
ftp.connect(host, port);
} catch (UnknownHostException ex) {
LOGGER.error("找不到FTP服务器【" + host + "】");
} catch (SocketTimeoutException e) {
LOGGER.error("连接FTP服务器【" + host + "】超时!");
}

// 检测连接FTP服务器是否成功
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
disconnect();
LOGGER.error("连接FTP服务器【" + host + "】失败!");
}

// 登录
if (!ftp.login(StringUtils.isEmpty(user) ? ANONYMOUS_LOGIN : user, password)) {
is_connected = false;
disconnect();
LOGGER.error("登录FTP服务器【" + host + "】失败!请检查用户名和密码!");
} else {
is_connected = true;
}

// 设置数据转换类型
if (isTextMode) {
ftp.setFileType(FTP.ASCII_FILE_TYPE);
} else {
ftp.setFileType(FTP.BINARY_FILE_TYPE);
}
LOGGER.info("连接FTP服务器【" + host + "】成功!");
}

/**
* 上传文件
*
* @author zcq
* @param ftpFileName
* @param localFile
* @throws IOException
*/
public void upload(String ftpFileName, File localFile) throws IOException {
// 检查文件是否存在
if (!localFile.exists()) {
LOGGER.error("该文件【" + localFile.getAbsolutePath() + "】不存在!");
}
// 上传操作
InputStream in = null;
try {
// 使用被动模式通过防火墙
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory(this.getWorkingDirectory());
in = new BufferedInputStream(new FileInputStream(localFile));
if (!ftp.storeFile(ftpFileName, in)) {
LOGGER.error("上传文件【" + ftpFileName + "】失败!请检查用户权限和文件路径!");
}
} finally {
try {
in.close();
} catch (IOException ex) {
}
}
}

/**
* 下载文件
*
* @author zcq
* @param ftpFileName
* @param localFile
* @throws IOException
*/
public void download(String ftpFileName, File localFile) throws IOException {
// 下载文件
OutputStream out = null;
try {
// 使用被动模式通过防火墙
ftp.enterLocalPassiveMode();
// 获取文件信息
FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName);
if (fileInfoArray == null) {
LOGGER.error("该文件【" + ftpFileName + "】未能在FTP服务器上找到!");
}
// 检查文件大小
FTPFile fileInfo = fileInfoArray[0];
long size = fileInfo.getSize();
if (size > Integer.MAX_VALUE) {
LOGGER.error("文件【" + ftpFileName + "】太大!");
}
// 下载操作
out = new BufferedOutputStream(new FileOutputStream(localFile));
if (!ftp.retrieveFile(ftpFileName, out)) {
LOGGER.error("下载文件【" + ftpFileName + "】失败!请检查用户权限和文件路径!");
}
out.flush();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
}
}
}
}

/**
* 删除文件
*
* @author zcq
* @param ftpFileName
* @throws IOException
*/
public void remove(String ftpFileName) throws IOException {
if (!ftp.deleteFile(ftpFileName)) {
LOGGER.error("删除文件【" + ftpFileName + "】失败!");
}
}

/**
* 列出指定FTP目录下的文件
*
* @author zcq
* @param filePath
* @return
* @throws IOException
*/
public List<String> list(String filePath) throws IOException {
List<String> fileList = new ArrayList<String>();
// 使用被动模式通过防火墙
ftp.enterLocalPassiveMode();

FTPFile[] ftpFiles = ftp.listFiles(filePath);
int size = (ftpFiles == null) ? 0 : ftpFiles.length;
for (int i = 0; i < size; i++) {
FTPFile ftpFile = ftpFiles[i];
if (ftpFile.isFile()) {
fileList.add(ftpFile.getName());
}
}
return fileList;
}

/**
* 发送一个FTP服务器站点特定的命令
*
* @author zcq
* @param args
* @throws IOException
*/
public void sendSiteCommand(String args) throws IOException {
if (ftp.isConnected()) {
try {
ftp.sendSiteCommand(args);
} catch (IOException ex) {
}
}
}

/**
* 断开FTP服务器连接
*
* @author zcq
* @throws IOException
*/
public void disconnect() throws IOException {
if (ftp.isConnected()) {
try {
ftp.logout();
ftp.disconnect();
is_connected = false;
} catch (IOException ex) {
}
}
}

/**
* 创建文件在FTP服务器上的完整名称
*
* @author zcq
* @param ftpPath
* @param localFile
* @return
*/
public String makeFTPFileName(String ftpPath, File localFile) {
if (ftpPath == "") {
return localFile.getName();
} else {
String path = ftpPath.trim();
if (path.charAt(path.length() - 1) != '/') {
path = path + "/";
}

return path + localFile.getName();
}
}

/**
* 测试是否连接上FTP服务器
*
* @author zcq
* @return
*/
public boolean isConnected() {
return is_connected;
}

/**
* 获取当前工作目录
*
* @author zcq
* @return
*/
public String getWorkingDirectory() {
if (!is_connected) {
return "";
}

try {
return ftp.printWorkingDirectory();
} catch (IOException e) {
}

return "";
}

/**
* 设置当前工作目录
*
* @author zcq
* @param dir
* @return
*/
public boolean setWorkingDirectory(String dir) {
if (!is_connected) {
return false;
}

try {
return ftp.changeWorkingDirectory(dir);
} catch (IOException e) {
}

return false;

4000
}

/**
* 更改工作目录的父目录上的FTP服务器路径
*
* @author zcq
* @return
*/
public boolean setParentDirectory() {
if (!is_connected) {
return false;
}

try {
return ftp.changeToParentDirectory();
} catch (IOException e) {
}

return false;
}

/**
* 获取父目录
*
* @author zcq
* @return
*/
public String getParentDirectory() {
if (!is_connected) {
return "";
}

String w = getWorkingDirectory();
setParentDirectory();
String p = getWorkingDirectory();
setWorkingDirectory(w);

return p;
}

/**
* 下载FTP服务器指定文件流
*
* @author zcq
* @param ftpFileName
* @param out
* @throws IOException
*/
public void getFile(String ftpFileName, OutputStream out) throws IOException {
try {
// 使用被动模式通过防火墙
ftp.enterLocalPassiveMode();

// 获取文件信息
FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName);
if (fileInfoArray == null) {
LOGGER.error("该文件【" + ftpFileName + "】未能在FTP服务器上找到!");
}

// 检查文件大小
FTPFile fileInfo = fileInfoArray[0];
long size = fileInfo.getSize();
if (size > Integer.MAX_VALUE) {
LOGGER.error("文件【" + ftpFileName + "】太大!");
}

// 下载文件
if (!ftp.retrieveFile(ftpFileName, out)) {
LOGGER.error("下载文件【" + ftpFileName + "】失败!请检查用户权限和文件路径!");
}
out.flush();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
}
}
}
}

/**
* 上传指定文件流放到FTP服务器上
*
* @author zcq
* @param ftpFileName
* @param in
* @throws IOException
*/
public void putFile(String ftpFileName, InputStream in) throws IOException {
try {
// 使用被动模式通过防火墙
ftp.enterLocalPassiveMode();

if (!ftp.storeFile(ftpFileName, in)) {
LOGGER.error("上传文件【" + ftpFileName + "】失败!请检查用户权限和文件路径!");
}
} finally {
try {
in.close();
} catch (IOException ex) {
}
}
}

// =========================================自定义方法==============================================

/**
* 写入文件
*
* @author zcq
* @param result
*/
public void writeFile(String filePath, String result) {
try {
FileUtils.writeStringToFile(new File(filePath), result, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 读取文件
*
* @author zcq
* @param result
* @return
*/
public String readFile(String path) {
String sql = "";
try {
sql = FileUtils.readFileToString(new File(path), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return sql;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐