package com.nlteck.util;
import java.io.BufferedInputStream;
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.SocketException;
import java.util.Iterator;
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 com.nlteck.util.CommonUtil;
/**
* FTP工具类
*
* @author Administrator
*
*/
public class FtpUtil {
private static FTPClient ftpClient = new FTPClient();
private static String encoding = System.getProperty("file.encoding");
/**
* 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 uploadFile2(String host, int port, String username, String password,
String filePath, File[] originFiles, String chmodPath, StringBuffer errInfo) {
boolean result = true;
BufferedInputStream in = null;
try {
int reply;
ftpClient.connect(host, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftpClient.login(username, password);// 登录
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return result;
}
String[] dirs = filePath.split("/");
//防止文件夹被意外的限制无权限上传
try {
errInfo.append("CHMOD 777 /" + chmodPath + " -R \n");
ftpClient.site("CHMOD 777 /" + chmodPath + " -R");
errInfo.append("end \n");
} catch (Exception e) {
errInfo.append(CommonUtil.getThrowableException(e));
return false;
}
//切换到上传目录
if (!ftpClient.changeWorkingDirectory(filePath)) {
//如果目录不存在创建目录
String tempPath = "";
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.setBufferSize(1024*1024);
//设置上传文件的类型为二进制类型
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileInputStream fis = null;
for(File orgin : originFiles) {
try {
fis = new FileInputStream(orgin.getAbsolutePath());
//为了加大上传文件速度,将InputStream转成BufferInputStream
in = new BufferedInputStream(fis);
//上传文件
if (!ftpClient.storeFile(new String(orgin.getName().getBytes("utf-8"), "iso-8859-1"), in)) {
result = false;
errInfo.append("name:" + orgin.getName() + ",上传失败!\n");
}
} catch (Exception e) {
result = false;
errInfo.append(CommonUtil.getThrowableException(e));
} finally {
if(fis != null) {
fis.close();
}
if(in != null) {
in.close();
}
}
}
} catch (IOException e) {
result = false;
errInfo.append(CommonUtil.getThrowableException(e));
} finally {
try {
ftpClient.logout();
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static boolean uploadFile(String url, int port, String username, String password, String path,
String filename, InputStream input) {
boolean result = false;
try {
int reply;
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftpClient.connect(url);
// ftp.connect(url, port);// 连接FTP服务器
// 登录
ftpClient.login(username, password);
ftpClient.setControlEncoding("utf-8");
ftpClient.enterLocalPassiveMode();
// 检验是否连接成功
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
System.out.println("连接失败");
ftpClient.disconnect();
return result;
}
/**如果文件夹不存在,则ftp新建文件夹*/
//if(!isDirExist(ftpClient, path)) {
createDirs(ftpClient, path);
// 转移工作目录至指定目录下
boolean change = ftpClient.changeWorkingDirectory(path);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (change) {
result = ftpClient.storeFile(new String(filename.getBytes("utf-8"), "iso-8859-1"), input);
}
input.close();
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
/**
* 创建多级目录
* @param ftp 一个连接有效的ftp连接
* @param path 可能需要创建的多级目录路径,/分隔
*/
public static void createDirs(FTPClient ftp , String path){
/*该部分为逐级创建*/
String[] split = path.split("/");
try {
for (String name : split) {
if(CommonUtil.isNullOrEmpty(name)) {
continue;
}
if (!ftp.changeWorkingDirectory(name)) {
//System.out.println("FTP: 目录不存在");
boolean makeDirectory = ftp.makeDirectory(name);
boolean changeWorkingDirectory = ftp.changeWorkingDirectory(name);
//System.out.println(name + "FTP: 创建结果:" + makeDirectory + ";切换工作目录结果:" + changeWorkingDirectory);
}// else {
//System.out.println("目录已存在");
// }
}
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 从ftp服务器下载指定的文件
*
* @param url
* @param port
* @param username
* @param password
* @param remotePath
* @param fileName
* @param localPath
* @return
*/
public static boolean downFile(String url, int port, String username, String password, String remotePath,
String fileName, String localPath) {
boolean result = false;
try {
int reply;
ftpClient.setControlEncoding(encoding);
ftpClient.connect(url); // 默认连接
ftpClient.login(username, password);// 登录
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 设置文件传输方式
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
return result;
}
// 转移到FTP服务器目录至指定的目录下
//
boolean changeResult = ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
System.out.println("change working directory " + changeResult);
ftpClient.enterLocalPassiveMode();
FTPFile[] fs = ftpClient.listFiles(); // 获取下载文件列表
boolean downloadResult = true;
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
System.out.println("ftpClient connect state = " + ftpClient.isConnected());
//new String(ff.getName().getBytes(encoding),"iso-8859-1")
boolean b = ftpClient.retrieveFile(ff.getName(), is);
System.out.println("download file " + b);
is.close();