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

ftpClient(apache提供的commons-net-3.3)

2017-01-12 18:16 302 查看
1jar包

apache提供的commons-net-3.3.jar

2
package com.xxx.common.util;

import org.apache.commons.lang.StringUtils;
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.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;

/**
*   ftp工具类
*/
public class FTPServiceUtil implements java.io.Serializable {

private Log logger = LogFactory.getLog(FTPClientUtil.class);
private String host;
private int port;
private String userName;
private String passWord;
private boolean binaryTransfer = true;//是否二进制
private boolean passiveMode = true;//解决linux上出现假死的状况
private String encoding = "UTF-8";
private int clientTimeout = 5000;
private boolean flag = true;

private FTPClient ftpClient;

private FTPServiceUtil(String host, int port, String userName, String passWord) {
this.host = host;
this.port = port;
this.userName = userName;
this.passWord = passWord;
}

public static FTPServiceUtil getFtpServiceUtil(String host, int port, String userName, String passWord) {
return new FTPServiceUtil(host, port, userName, passWord);
}

public boolean folderIsExist(String path) {
String workDirectory = "";
try {
workDirectory = ftpClient.printWorkingDirectory();
File file = new File(path);
String fileName = file.getName();
//判断最后一级是否是文件名称
if (fileName.indexOf(".") > -1) {
//是文件
path = path.replace(fileName, "");
}
if (ftpClient.cwd(path) == 250) {
ftpClient.cwd(workDirectory);//恢复到原工作目录
return true;
} else
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

public void ftpLogin() throws Exception {
if (ftpClient == null) {
ftpClient = new FTPClient();
}
ftpClient.connect(this.host, this.port);
FTPClientConfig clientConfig = new FTPClientConf
4000
ig(FTPClientConfig.SYST_UNIX);
ftpClient.configure(clientConfig);
ftpClient.setControlEncoding(encoding);
if (!ftpClient.login(userName, passWord)) {
throw new Exception("FTP无法登陆:[userName:" + this.userName + ",password:" + this.passWord + "]");
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setConnectTimeout(100*60);
ftpClient.setSoTimeout(100*60);
ftpClient.enterLocalPassiveMode();
// 连接后检测返回码来校验连接是否成功
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new Exception("FTP连接失败:[userName:" + this.userName + ",password:" + this.passWord + "]");

}
}

/**
* 上传一个本地文件到远程指定文件
*
* @param serverFile 服务器端文件名(包括完整路径)
* @param localFile  本地文件名(包括完整路径)
* @return 成功时,返回true,失败返回false
* @throws Exception
*/
public boolean put(String serverFile, String localFile) throws Exception {
return put(serverFile, localFile, false);
}

public boolean put(String serverFile, String localFile, boolean delFile) throws Exception {
InputStream input = null;
try {
// 处理传输
input = new FileInputStream(localFile);
ftpClient.storeFile(serverFile, input);
if (delFile) {
(new File(localFile)).delete();
}
return true;
} catch (Exception e) {
throw new Exception("Could not put file to server.", e);
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 下载一个远程文件返回流
* 处理完后记得关闭流
*
* @param serverFile
* @return
* @throws Exception
*/
public InputStream get(String serverFile) throws Exception {
return get(serverFile, false);
}

/**
* 下载一个远程文件返回流
* 处理完后记得关闭流
*
* @param serverFile
* @param delFile    读取完成后是否删除FTP上的源文件
* @return InputStream
* @throws Exception
*/
public InputStream get(String serverFile, boolean delFile) throws Exception {
InputStream is = null;
try {
// 处理传输
is = ftpClient.retrieveFileStream(serverFile);
if (delFile) { // 删除远程文件
ftpClient.deleteFile(serverFile);
}
} catch (IOException e) {
throw new Exception("Couldn't get file from server.", e);
}
return is;
}

public boolean get(String serverFile, String localFile, boolean delFile) throws Exception {
OutputStream output = null;
String path = localFile.replaceAll("\\.[a-zA-Z1-9]+$", "");
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
try {
output = new FileOutputStream(localFile);
return get(serverFile, output, delFile);
} catch (FileNotFoundException e) {
throw new Exception("local file not found.", e);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 列出远程目录下所有的文件
*
* @param remotePath 远程目录名
* @return 远程目录下所有文件名的列表,目录不存在或者目录下没有文件时返回0长度的数组
* @throws Exception
*/
public String[] listNames(String remotePath) throws Exception {
try {
String[] listNames = ftpClient.listNames(remotePath);
return listNames;
} catch (IOException e) {
throw new Exception("列出远程目录下所有的文件时出现异常", e);
}
}

public boolean changeWorkingDirectory(String directory) throws Exception {
boolean isChange = ftpClient.changeWorkingDirectory(directory);
return isChange;
}

public String printWorkingDirectory() throws Exception {
String workDirectory = this.ftpClient.printWorkingDirectory();
return workDirectory;
}

public boolean createRecursionDirectory(String baseDirectory, String directory) throws Exception {
try {
ftpClient.changeWorkingDirectory(baseDirectory);
String[] directionName = directory.split("/");
for (int i = 0; i < directionName.length; i++) {
if (StringUtils.isNotEmpty(directionName[i])) {
System.out.println(ftpClient.printWorkingDirectory());
if (!ftpClient.changeWorkingDirectory(directionName[i])) {
boolean isSucess = ftpClient.makeDirectory(directionName[i]);
if (isSucess) {
ftpClient.changeWorkingDirectory(directionName[i]);
} else {
logger.error("create directory fail,dirName=" + directionName[i]);
return false;
}
}
}
}

} catch (Exception e) {
logger.error("createRecursionDirectory error", e);
return false;
}
return true;
}

public boolean createRecursionDirectory(String directory) throws Exception {
try {
ftpClient.changeWorkingDirectory("/");
String[] directionName = directory.split("/");
for (int i = 0; i < directionName.length; i++) {
if (StringUtils.isNotEmpty(directionName[i])) {
System.out.println(ftpClient.printWorkingDirectory());
if (!ftpClient.changeWorkingDirectory(directionName[i])) {
boolean isSucess = ftpClient.makeDirectory(directionName[i]);
if (isSucess) {
ftpClient.changeWorkingDirectory(directionName[i]);
} else {
logger.error("create directory fail,dirName=" + directionName[i]);
return false;
}
}
}
}

} catch (Exception e) {
logger.error("createRecursionDirectory error", e);
return false;
}
return true;
}

/**
* 在FTP上创建目录,支持路径中包含文件名称
*
* @param path 目录路径
* @return boolean
* true 创建成功,false 创建失败
*/
public boolean makeDirectory(String path) {
try {
File file = new File(path);
String fileName = file.getName();
//判断路径中是否包含了文件名称
if (fileName.indexOf(".") > -1) {
//包含文件
path = path.replace(fileName, "");
}
return ftpClient.makeDirectory(path);
} catch (Exception e) {
return false;
}
}

public boolean get(String serverFile, OutputStream output, boolean delFile) throws Exception {
try {
// 处理传输
ftpClient.retrieveFile(serverFile, output);
if (delFile) { // 删除远程文件
ftpClient.deleteFile(serverFile);
}
return true;
} catch (IOException e) {
throw new Exception("Couldn't get file from server.", e);
}
}

/**
* 批量删除
*
* @param delFiles
* @return
* @throws Exception
*/
public boolean delete(String[] delFiles) throws Exception {
try {
for (String s : delFiles) {
ftpClient.deleteFile(s);
}
return true;
} catch (IOException e) {
throw new Exception("Couldn't delete file from server.", e);
}
}

/**
* 获取ftp文件输出流
*
* @param remotePath ftp远程目录路径.支持带文件名称的路径
* @return OutputStream
*/
public OutputStream storeFileStream(String remotePath) {
OutputStream outputStream = null;
try {
outputStream = ftpClient.storeFileStream(remotePath);
return outputStream;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* 获取ftp文件输出流
*
* @param remotePath ftp远程目录路径.支持带文件名称的路径
* @return OutputStream
*/
public boolean storeFile(String fileName, InputStream inputStream) {

try {
boolean b = ftpClient.storeFile(fileName, inputStream);
return b;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 从ftp服务器上删除一个文件
*
* @param delFile
* @return
* @throws Exception
*/
public boolean delete(String delFile) throws Exception {
try {
ftpClient.deleteFile(delFile);
return true;
} catch (IOException e) {
throw new Exception("Couldn't delete file from server.", e);
}
}

public void ftpLogout() throws Exception {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
ftpClient = null;
}

}

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