记录下自己写好已经使用的工具类,便于以后使用
package cn.com.sandpay.sandbase.util;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* 定义Ftp工具类,提供Ftp上送、下载、读取的方法。
*
* @author
*
* @version 1.0 2016-02-14
*
* @since JDK 1.6 以上
*
* @category
* */
public class FtpUtil {
private static Log log = LogFactory.getLog(FtpUtil.class);
//定义工具使用的常量
private FTPClient ftpClient = null; //FTP对象
private String ip = ""; //FTP服务器
private String username = ""; //FTP用户名
private String password = ""; //FTP密码
private int port = -1; //FTP端口
private String path = ""; //FTP定位
private String dir = ""; //FTP目录
private OutputStream os = null; //输出流对象
private FileInputStream is = null; //文件流对象
/**
* 从配置文件中读取FTP配置信息,创建FTP对象
* 配置文件为ftp.properties
* */
public FtpUtil(){
try {
InputStream in = FtpUtil.class.getResourceAsStream("/ftp.properties");
Properties p = new Properties();
p.load(in);
in.close();
this.ip = p.getProperty("ftpUtil.ip");
this.password = p.getProperty("ftpUtil.password");
this.username = p.getProperty("ftpUtil.username");
this.dir = p.getProperty("ftpUtil.dir");
} catch (Exception e) {
e.printStackTrace();
}
}
public FtpUtil(String serverIP, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
}
public FtpUtil(String serverIP, int port, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
this.port = port;
}
public FtpUtil(String serverIP, String username, String password, String dir){
this.ip = serverIP;
this.username = username;
this.password = password;
this.dir = dir;
}
/**
* 连接ftp服务器
*
* @throws IOException
*/
public boolean connectServer(){
try {
if(ftpClient == null){
ftpClient = new FTPClient();
}
//判断客户端当前是否连接到服务器
if(ftpClient.isConnected()){
return false;
}
//连接
if(this.port != -1){
ftpClient.connect(this.ip, this.port);
}else{
ftpClient.connect(this.ip);
}
//文件类型,默认是ASCII
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//设置格式
if(FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))){
ftpClient.setControlEncoding("UTF-8");
}else{
ftpClient.setControlEncoding("GBK");
}
ftpClient.enterLocalActiveMode();
//登录
ftpClient.login(this.username, this.password);
//验证是否连接登录成功
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
ftpClient.disconnect(); //销毁对象
return false;
}
//进入指定目录
if(this.path.length() != 0){
ftpClient.changeWorkingDirectory(this.path);
}
log.error("已登录到\"" + ftpClient.printWorkingDirectory() + "\"目录");
return true;
}catch (IOException e){
//e.printStackTrace();
log.info("连接FTP失败,失败原因:" + e.getMessage());
return false;
}
}
/**
* 到指定目录
* */
public boolean changefload(String path){
try {
ftpClient.changeWorkingDirectory(path);
System.out.println(ftpClient.printWorkingDirectory());
log.error("已登录到\"" + ftpClient.printWorkingDirectory() + "\"目录");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 断开与ftp服务器连接
*
* @throws IOException
*/
public boolean closeServer(){
try{
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
log.error("已从服务器断开");
return true;
}catch(IOException e){
e.printStackTrace();
return false;
}
}
/**
* 检查文件夹在当前目录下是否存在
* @param dir
* @return
*/
private boolean isDirExist(String dir){
try {
return ftpClient.changeWorkingDirectory(dir);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 在当前目录下创建文件夹
* @param dir
* @return
* @throws Exception
*/
private boolean createDir(String dir){
try{
StringTokenizer s = new StringTokenizer(dir, "/"); //sign
s.countTokens();
String pathName = ftpClient.printWorkingDirectory();
while(s.hasMoreElements()){
String createName = (String) s.nextElement();
pathName = pathName + "/" +createName;
if(!isDirExist(pathName)){
ftpClient.makeDirectory(createName);
ftpClient.changeWorkingDirectory(pathName);
}
}
return true;
}catch (IOException e1){
e1.printStackTrace();
return false;
}
}
/**
* ftp上传
* 如果服务器段已存在名为filename的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
*
* @param filename 要上传的文件(或文件夹)名
* @return
* @throws Exception
*/
public boolean upload(String filename){
String newname = "";
if(filename.indexOf("/") > -1){
newname = filename.substring(filename.lastIndexOf("/") + 1);
}else{
newname = filename;
}
return upload(filename, newname);
}
/**
* ftp上传
* 如果服务器段已存在名为newName的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
*
* @param fileName 要上传的文件(或文件夹)名
* @param newName 服务器段要生成的文件(或文件夹)名
* @return
*/
public boolean upload(String fileName, String newName){
try{
String savefilename = fileName;
if(fileName.equals(new String(fileName.getBytes("ISO-8859-1"), "ISO-8859-1"))){
savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");
}
File file_in = new File(savefilename);//打开本地待长传的文件
if(!file_in.exists()){
throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");
}
if(file_in.isDirectory()){
upload(file_in.getPath(),newName,ftpClient.printWorkingDirectory());
}else{
uploadFile(file_in.getPath(),newName);
}
return true;
}catch(Exception e){
e.printStackTrace();
System.err.println("Exception e in Ftp upload(): " + e.toString());
return false;
}
}
/**
* 上传文件夹的方法
* @param fileName
* @param newName
* @param path
* @throws Exception
*/
private void upload(String fileName, String newName,String path) throws Exception{
String savefilename = fileName;
if(fileName.equals(new String(fileName.getBytes("ISO-8859-1"), "ISO-8859-1"))){
savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");
}
File file_in = new File(savefilename);//打开本地待长传的文件
if(!file_in.exists()){
throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");
}
if(file_in.isDirectory()){
if(!isDirExist(newName)){
createDir(newName);
}
ftpClient.changeWorkingDirectory(newName);
File sourceFile[] = file_in.listFiles();
for(int i = 0; i < sourceFile.length; i++){
if(!sourceFile[i].exists()){
continue;
}
if(sourceFile[i].isDirectory()){
this.upload(sourceFile[i].getPath(),sourceFile[i].getName(),path+"/"+newName);
}else{
this.uploadFile(sourceFile[i].getPath(),sourceFile[i].getName());
}
}
}else{
uploadFile(file_in.getPath(),newName);
}
ftpClient.changeWorkingDirectory(path);
}
/**
* upload 上传文件
*
* @param filename 要上传的文件名
* @param newname 上传后的新文件名
* @return -1 文件不存在 >=0 成功上传,返回文件的大小
* @throws Exception
*/
public long uploadFile(String filename, String newname) throws Exception{
long result = 0;
InputStream is = null;
OutputStream os = null;
try {
File file_in = new File(filename);
if(!file_in.exists())
return -1;
os = ftpClient.storeFileStream(newname);
result = file_in.length();
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while((c = is.read(bytes)) != -1){
os.write(bytes, 0, c);
}
}finally{
if(is != null){
is.close();
}
if(os != null){
os.close();
}
}
return result;
}
/**
* 为Excel专门提供的上传方法,
* 由于FTPClient的问题,上传Excel和上传CSV、TXT不同,需要其他配置
*
* @param finename 本地Excel文件
*
* @param newname 上送FTP后的Excel文件名称
*
* @author 尚吉存
* */
public long uploadExcelFile(String filename, String newname) throws Exception{
long result = 0;
InputStream is = null;
OutputStream os = null;
try {
File file_in = new File(filename);
if(!file_in.exists())
return -1;
//设置PassiveMode传输
ftpClient.enterLocalPassiveMode();
//设置以二进制流的方式传输
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
is = new FileInputStream(file_in);
boolean flag = ftpClient.storeFile(newname, is);
if(flag){
log.info("上送Excel文件成功!");
result = 1;
}else{
log.info("上送Excel文件失败!");
}
}finally{
if(is != null){
is.close();
}
if(os != null){
os.close();
}
}
return result;
}
/**
* 从ftp下载文件到本地
*
* @param filename 服务器上的文件名
* @param newfilename 本地生成的文件名
* @return
* @throws Exception
*/
public long downloadFile(String filename, String newfilename){
long result = 0;
FileOutputStream os = null;
InputStream is = null;
try{
is = ftpClient.retrieveFileStream(filename);
is.close();
ftpClient.completePendingCommand();
File outfile = new File(newfilename);
os = new FileOutputStream(outfile);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
result = result + c;
}
log.info("共下载了" + result +"字节文件");
}catch (IOException e){
e.printStackTrace();
}finally{
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 取得相对于当前连接目录的某个目录下所有文件列表
*
* @param path
* @return
*/
public List<String> getFileList(String path){
List<String> fileList = new ArrayList<String>();
try {
String filePath = ftpClient.printWorkingDirectory()+"/"+this.path + dir;
List<FTPFile> ftpFiles = Arrays.asList(ftpClient.listFiles(filePath));
if(ftpFiles == null || ftpFiles.size() == 0) {
return fileList;
}
for(FTPFile ftpFile : ftpFiles) {
if(path.endsWith("/")){
fileList.add(path.substring(0,path.length()-1) +"/"+ftpFile.getName());
}else{
fileList.add(path +"/"+ftpFile.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return fileList;
}
/**
* 返回一个输入流,用来获取数据而无需下载至本地
*
* @param path
* @return
* @throws IOException
*/
public InputStream getInputStream(String remoteFilePath) throws Exception {
InputStream is = ftpClient.retrieveFileStream(remoteFilePath);
//复制InputStream后关闭
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) > -1 ) {
baos.write(buffer, 0, len);
}
baos.flush();
InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());
//顺序必须正常,少一个都会出现异常
is.close();
ftpClient.completePendingCommand();
return stream1;
}
/**
* 得到指定目录下指定前缀的表格文件
*
* @param path
* @return
*/
public List<String> getExcelFileListByPrefix(String prefix){
List<String> list = new ArrayList<String>();
try {
String filePath = ftpClient.printWorkingDirectory()+"/"+this.path + dir;
List<FTPFile> ftpfiles = Arrays.asList(ftpClient.listFiles(filePath));
for (FTPFile ftpFile : ftpfiles) {
String filename = ftpFile.getName();
if(filename.startsWith(prefix) && (filename.endsWith(".xlsx")||filename.endsWith(".xls"))){
if(dir.endsWith("/")){
list.add(dir.substring(0,dir.length()-1) +"/"+ftpFile.getName());
}else{
list.add(dir + "/" +filename);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 得到当前连接目录的某个目录下指定前缀的表格文件
*
* @param path
* @return
*/
public List<String> getExcelFileListByPrefix2(String prefix,String dir){
List<String> list = new ArrayList<String>();
try {
String filePath = ftpClient.printWorkingDirectory()+"/"+this.path + dir;
List<FTPFile> ftpfiles = Arrays.asList(ftpClient.listFiles(filePath));
for (FTPFile ftpFile : ftpfiles) {
String filename = ftpFile.getName();
if(filename.startsWith(prefix) && (filename.endsWith(".xlsx")||filename.endsWith(".xls"))){
if(dir.endsWith("/")){
list.add(dir.substring(0,dir.length()-1) + "/" + filename);
}else{
list.add(dir + "/" + filename);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 得到指定目录下指定前缀的文本文件集
*
* @param path
* @return
*/
public List<String> getTextFileListByPrefix(String prefix){
List<String> list = new ArrayList<String>();
try {
String filePath = ftpClient.printWorkingDirectory()+"/"+this.path + dir;
List<FTPFile> ftpfiles = Arrays.asList(ftpClient.listFiles(filePath));
for (FTPFile ftpFile : ftpfiles) {
String filename = ftpFile.getName();
if((filename.startsWith(prefix) && (filename.endsWith(".txt")))||
(filename.startsWith(prefix) && (filename.endsWith(".TXT")))){
if(dir.endsWith("/")){
list.add(dir.substring(0,dir.length()-1) + "/" + filename);
}else{
list.add(dir + "/" + filename);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 得到指定目录下指定前缀的文本文件集
*
* @param prefix 文件名称
*
* @param dir 文件所在文件夹名称
*
* @return 文件名称集
*
* @author shang.jc Copy sandbase.util 2015-06-05
*/
public List<String> getTextFileListByPrefix(String prefix,String dir){
List<String> list = new ArrayList<String>();
try {
String filePath = ftpClient.printWorkingDirectory()+"/"+this.path + dir;
List<FTPFile> ftpfiles = Arrays.asList(ftpClient.listFiles(filePath));
for (FTPFile ftpFile : ftpfiles) {
String filename = ftpFile.getName();
if((filename.startsWith(prefix) && (filename.endsWith(".txt")))||
(filename.startsWith(prefix) && (filename.endsWith(".TXT")))){
if(dir.endsWith("/")){
list.add(dir.substring(0,dir.length()-1) + "/" + filename);
}else{
list.add(dir + "/" + filename);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 得到指定目录下指定前缀的文本文件集
*
* @param path
* @return
*/
public List<String> getCsvFileListByPrefix(String prefix){
List<String> list = new ArrayList<String>();
try {
String filePath = ftpClient.printWorkingDirectory()+"/"+this.path + dir;
List<FTPFile> ftpFiles = Arrays.asList(ftpClient.listFiles(filePath));
for (FTPFile ftpFile : ftpFiles) {
String filename = ftpFile.getName();
if((filename.startsWith(prefix) && (filename.endsWith(".csv")))||
(filename.startsWith(prefix) && (filename.endsWith(".CSV")))){
if(dir.endsWith("/")){
list.add(dir.substring(0,dir.length()-1) + "/" + filename);
}else{
list.add(dir + "/" + filename);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 得到指定目录下指定前缀的文本文件集
*
* @param path
* @return
*/
public List<String> getCsvFileListByPrefix2(String prefix,String dir){
List<String> list = new ArrayList<String>();
try {
String filePath = ftpClient.printWorkingDirectory()+"/"+this.path + dir;
List<FTPFile> ftpfiles = Arrays.asList(ftpClient.listFiles(filePath));
for (FTPFile ftpFile : ftpfiles) {
String filename = ftpFile.getName();
if((filename.startsWith(prefix) && (filename.endsWith(".csv")))||
(filename.startsWith(prefix) && (filename.endsWith(".CSV")))){
if(dir.endsWith("/")){
list.add(dir.substring(0,dir.length()-1) + "/" + filename);
}else{
list.add(dir + "/" + filename);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 修改文件名
*
* @param path
* @return
* @throws IOException
*/
public boolean modFileName(String oldName, String newName) throws IOException{
return ftpClient.rename(oldName, newName);
}
/**
* 上送文件至指定的FTP目录
*
* @param path
* @return
* @throws IOException
*/
public String uploadCsv2Server(String columns, String data, String csvFileName) {
csvFileName = csvFileName.replace('/', File.separatorChar);
try {
OutputStream os = ftpClient.storeFileStream(csvFileName);
OutputStreamWriter writer = new OutputStreamWriter(os, "gbk");
BufferedWriter bw = new BufferedWriter(writer);
bw.write((new StringBuilder()).append(columns).append(data).toString());
bw.newLine();
bw.flush();
bw.close();
return "0";
} catch (Exception e) {
System.out.println(e.getMessage());
log.info(e.getMessage());
return e.getMessage();
}
}
/**
* 上送文件至指定的FTP目录<br/>
* 这里去掉newLine <br/>
*
* @param columns 表头
* @param data 内容
* @param csvFileNmae 文件名称
*
* @return
* @throws IOException
*/
public String uploadFileToServer(String columns, String data, String csvFileName) {
csvFileName = csvFileName.replace('/', File.separatorChar);
try {
OutputStream os = ftpClient.storeFileStream(csvFileName);
OutputStreamWriter writer = new OutputStreamWriter(os, "gbk");
BufferedWriter bw = new BufferedWriter(writer);
bw.write((new StringBuilder()).append(columns).append(data).toString());
//bw.newLine();
bw.flush();
bw.close();
return "0";
} catch (Exception e) {
System.out.println(e.getMessage());
log.info(e.getMessage());
return e.getMessage();
}
}
}