ftp上传工具类

来源:互联网 发布:js和jquery应用 编辑:程序博客网 时间:2024/04/29 20:13
package com.fms.xx.common;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;


import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FTPFile;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FileTransferClient;




public class UploadFileFtpUtils {


//Logger logger = Logger.getLogger(FtpUtils.class);

/**FTP文件服务器地址IP*/
private static String host = "";//
    /**FTP文件服务器登录账号*/
    private static String username = "";
    
    /**FTP文件服务器登录密码*/
    private static String password = "";
    /**FTP服务器端口*/
    private static int remotePort = 21;
    
    private FileTransferClient ftp;
    
    public FileTransferClient getFtp() {
return ftp;
}


static {
Map<String, String> ftpFileConfig = ContextUtil.config;// ContextUtil.config;
if(ftpFileConfig.size()!=0){
host = ftpFileConfig.get("host");
username = ftpFileConfig.get("username");
password = ftpFileConfig.get("password");
if (StringUtils.isNotBlank(ftpFileConfig.get("remotePort"))) {
remotePort = Integer.parseInt(ftpFileConfig.get("remotePort"));
} else {
remotePort = 21;
}
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception{
UploadFileFtpUtils ftps=new UploadFileFtpUtils();
try{
//ftps.copyFileAtFtp("D:/", "base/123.png", "upload/123.png");
ftps.connect();
//ftps.createRemoteDirectory("/ccccvcccccc");//新建文件夹
 
// ftps.delete("/Labview2013安装教程.docx",0);//0:文件  1:文件夹
// ftps.delete("/历史库",1);//0:文件  1:文件夹
//参数1:/当前库
// ftps.copyFileAtFtp("/","历史库/常用控件列表.doc","当前文件夹/abc.doc");//复制文件

//ftps.copyFileAtFtp("/","History/吴忠/1234-1.zip","Useing/吴忠/1234-12.zip");

ftps.upload("F:\\新增流速计算调用DLL参数说明Sheet1.pdf", "新增流速计算调用DLL参数说明Sheet1.pdf", "\\Images\\东华工程\\");  

}finally{
ftps.disconnect();
}
}

/**
* 创建文件夹树
* @param tree
* @param parentPath
* @throws FTPException
* @throws IOException
*/
public void createDirectoryByTree(Map<String,Map> tree,String parentPath) throws FTPException, IOException{
Set<String> nodeSet=tree.keySet();
if(nodeSet==null || nodeSet.size()==0)return;
for(String node:nodeSet){
if(!ftp.exists(parentPath+node+"/")){
ftp.createDirectory(parentPath+node+"/");
}
createDirectoryByTree(tree.get(node),parentPath+node+"/");
}
ftp.changeDirectory("/");
ftp.getRemoteDirectory();
}


/**
* 移动FTP文件
* @param sourceDirectory原路径
* @param targetDirectory目标路径
* @param fileName文件名
* @throws Exception
*/
public boolean move(String sourceDirectory,String targetDirectory,String fileName)throws Exception {
try{
if(!ftp.isConnected())ftp.connect();
ftp.changeDirectory("/");
//ftp.rename("北京海富泰工业设备有限公司/B1/14131/150312042422164.mpp", "北京海富泰工业设备有限公司/B1/14131/123.mpp");
if(ftp.exists(sourceDirectory+File.separator+fileName)){
if(createRemoteDirectory(targetDirectory)){
ftp.rename(sourceDirectory+File.separator+fileName,targetDirectory+File.separator+fileName);
}
}
return true;
}catch(Exception e){
//e.printStackTrace();
System.out.println("FtpUtils.java 89 Exception --"+e);
return false;
//throw e;
}finally{
this.disconnect();
}
}

/**
* 移动FTP文件
* @param sourcePath源文件全名
* @param targetPath目标目录全名
* @throws Exception
*/
public boolean move(String sourcePath,String targetPath)throws Exception {
try{
if(!ftp.isConnected())ftp.connect();
ftp.changeDirectory("/");
String targetDirectory=StringUtils.substringBeforeLast(targetPath, "/");
//ftp.rename("北京海富泰工业设备有限公司/B1/14131/150312042422164.mpp", "北京海富泰工业设备有限公司/B1/14131/123.mpp");
System.out.println(targetDirectory);
if(ftp.exists(sourcePath)){
if(createRemoteDirectory(targetDirectory)){
System.out.println("sourcePath:"+sourcePath);
System.out.println("targetPath:"+targetPath);
ftp.rename(sourcePath,targetPath);
}
}
return true;
}catch(Exception e){
//e.printStackTrace();
System.out.println("FtpUtils.java 89 Exception --"+e);
return false;
//throw e;
}finally{
this.disconnect();
}
}

/**
* 创建目录文件夹
* @param targetDirectory
* @return
* @throws FTPException
* @throws IOException
*/
public boolean createRemoteDirectory(String targetDirectory) throws FTPException, IOException {
try {
if(!ftp.isConnected())ftp.connect();
targetDirectory=targetDirectory.replace("\\\\", "/").replace("//", "/");
String[] direcs=StringUtils.split(targetDirectory, '/');
StringBuffer sb=new StringBuffer("");
for(int i=0;i<direcs.length;i++){
sb.append("/"+direcs[i]);
System.out.println(sb.toString());
if(!ftp.exists(sb.toString())){
ftp.createDirectory(sb.toString());
}
}
return true;
} finally {
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}

/**
* 批量创建文件夹树
* @param filePath
* @return
* @throws FTPException
* @throws IOException
*/
@SuppressWarnings("rawtypes")
public Map<String,Map> createDirectoryTree(List<String> filePath) throws FTPException, IOException {
try {
Map<String,Map> tree=new HashMap<String,Map>();
for (String path : filePath) {
path=StringUtils.substringBeforeLast(path.replace("\\", "/").replace("//", "/"),"/");//获取除文件名外的路径
System.out.println(path+"------------------------>");
String[] paths=StringUtils.split(path,"/");
setTree(tree,paths,0,paths.length-1);
}
return tree;
} finally {
}
}



@SuppressWarnings({ "rawtypes", "unchecked" })
private void setTree(Map<String, Map> tree, String[] paths ,int i,int max) {
//System.out.println("~~"+paths[i]+"-->"+i+":"+max);
try{
if(i==max-1 || i==max){
System.out.println(" ");
}
if(i>max)return;
if(tree.get(paths[i])==null){
System.out.println(""+paths[i]+"-->"+i+":"+max);
tree.put(paths[i], new HashMap<String,Map>());
}
setTree(tree.get(paths[i]),paths,1+i,max);
}catch(Exception e){
e.printStackTrace();
}
}


/**
* 批量移动FTP文件
* @param sourceDirectory
* @param targetDirectory
* @throws Exception
*/
public boolean move(List<String> oldPath,List<String> newPath)throws Exception {
if(ftp==null || !ftp.isConnected()) connect();
if(oldPath==null || newPath==null || oldPath.size()!=newPath.size()){
String msg=oldPath==null?"缺少原路径":(newPath==null?"缺少新路径":"路径数目不等");
throw new NullPointerException(msg);
}
try{
// createDirectoryTree(newPath);//先创建所有目录
createDirectoryByTree(createDirectoryTree(newPath),"/");
for (int i = 0; i < oldPath.size(); i++) {
String oldFilePath=oldPath.get(i);
String newFilePath=newPath.get(i);
if(!oldFilePath.equals(newFilePath)){//如果新目录和原目录不同,则转移文件位置
ftp.rename(oldFilePath, newFilePath);
// System.out.println(oldFilePath+"【】【】"+newFilePath);
}
}
return true;
}catch(Exception e){
System.out.println("FtpUtils.java 171 Exception --"+e);
e.printStackTrace();
return false;
}finally{
ftp.disconnect();
}
}
/**
* 上传单个文件
* @param localFilePath 本地文件路径
* @param remoteFileName 远程存放文件名称
* @param folderPath 存放文件的路径 /车型/车号/类型拼音/年/月/日/
*/
public void upload(String localFilePath, String remoteFileName,String folderPath) throws Exception {
try{
this.connect();
createDirectory(folderPath);
ftp.uploadFile(localFilePath, folderPath+ remoteFileName);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
this.disconnect();
}
}
/**
* 通过文件流信息上传文件
* @param inStream
* @param remoteFileName 远程存放文件名称
* @param folderPath 存放文件的路径 /车型/车号/类型拼音/年/月/日/
* @throws Exception
*/
public void upload(InputStream in, String remoteFileName,String folderPath) throws Exception {
try{
this.connect();
createDirectory(folderPath);
OutputStream out = ftp.uploadStream(folderPath + remoteFileName);
try {
IOUtils.copy(in, out);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
this.disconnect();
}
}

/**
* 下载单个文件
* @param localFilePath 本地文件路径
* @param remoteFilePath 远程存放路径
*/
public void download(String localFilePath, String remoteFilePath)throws Exception {
try{
this.connect();
ftp.downloadFile(localFilePath, remoteFilePath);
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
this.disconnect();
}
}

/**
* 下载文件
* @param output
* @param remoteFilePath
* @throws Exception
*/
public void download(OutputStream output, String remoteFilePath)throws Exception {
try{
byte[] data = ftp.downloadByteArray(remoteFilePath);
try{
IOUtils.write(data, output);
}catch(Exception e){
IOUtils.closeQuietly(output);
}
}catch(Exception e){
e.printStackTrace();
throw e;
}
}


public byte[] downloadByteArray(String remoteFilePath)throws Exception {
try{
byte[] data = ftp.downloadByteArray(remoteFilePath);
return data;
}catch(Exception e){
e.printStackTrace();
throw e;
}
}
/**
* 删除文件或文件夹
* @param remotePath 远程文件或文件夹路径
* @param type 0:文件   其他:文件夹
*/
public void delete(String remotePath,int type) throws Exception{
this.connect();
if(remotePath!=null && !"".equals(remotePath)){
if(type==0){
try{
ftp.deleteFile(remotePath);
}catch (Exception e) {
e.printStackTrace();
}
}else{
try{
ftp.deleteDirectory(remotePath);
}catch (Exception e) {
e.printStackTrace();
}
}
}
}

/**
* 创建文件夹
* @param path 存放的文件夹路径 /车型/车号/类型拼音/年/月/日/
*/
private void createDirectory(String folderPath) throws Exception {
this.connect();
String directory = ftp.getRemoteDirectory();

String[] fileNames = folderPath.split("/");
if(fileNames!=null&&fileNames.length!=0){
for(String fileName:fileNames){
if(null!=fileName&&!"".equals(fileName)){
boolean exist = existsDirectory(fileName);
if(!exist && !ftp.exists(fileName)){
ftp.createDirectory(fileName);
}
ftp.changeDirectory(fileName);
}

}
}
}
/**
* 判断目录是否存在
* @param remoteDirectory
* @return
* @throws Exception
*/
public  Boolean existsDirectory(String directoryName) throws Exception{
//当前目录
String directory = ftp.getRemoteDirectory();
try{
FTPFile[] files = ftp.directoryList( directoryName);
if(null==files||files.length==0){
return false;
}
return true;
}catch(Exception e){
return false;
}
}

/**
* 连接FTP服务器
* @throws FTPException 
* @throws IOException 
*/
public void connect() throws FTPException, IOException{
if(ftp==null||!ftp.isConnected()){
ftp = new FileTransferClient();
ftp.setRemoteHost(host);
ftp.setUserName(username);
ftp.setPassword(password); 
ftp.setRemotePort(remotePort);
ftp.setTimeout(3000);
//设置获取服务器端信息时所使用的编码
ftp.getAdvancedSettings().setControlEncoding("UTF-8");
// 被动模式,数据连接由客户端发起
ftp.getAdvancedFTPSettings().setConnectMode(FTPConnectMode.PASV);
//ftp.getAdvancedFTPSettings().setConnectMode(FTPConnectMode.ACTIVE);
// BINARY模式用来传送可执行文件,压缩文件,和图片文件.
ftp.setContentType(FTPTransferType.BINARY);
//设置传输缓冲区
ftp.getAdvancedSettings().setTransferBufferSize(1024);
//设置传输通知的时间间隔
ftp.getAdvancedSettings().setTransferNotifyInterval(5000);
ftp.setEventListener(new UploadListener(ftp)); 
ftp.connect();
}
}
/**
* 断开FTP服务器
* @throws FTPException
* @throws IOException
*/
public void disconnect(){
if(ftp!=null&&ftp.isConnected()){
try {
ftp.disconnect();
} catch (FTPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ftp = null;
}


public boolean exists(String srcdir)throws Exception {
return ftp.exists(srcdir);
}


public List<String> getChildrenFiles(String remotePath) throws FTPException, IOException{
return getChildrenFiles(remotePath,null);
}


public List<String> getChildrenFiles(String remotePath,List<String> pathList) throws FTPException, IOException {
if(pathList==null){
pathList=new ArrayList<String>();
}
String[] dictionary= null;
dictionary=ftp.directoryNameList(remotePath, false) ;
if(dictionary!=null && dictionary.length>0){
for (String child : dictionary) {
System.out.println(remotePath+File.separator+child);
if(ftp.exists(remotePath+File.separator+child)){
pathList.add(remotePath+File.separator+child);
getChildrenFiles(remotePath+File.separator+child,pathList);
}
}
}
return pathList;
}


/**
* 在FTP端复制文件
* @param filetempl
* @param path
* @throws IOException 
* @throws FTPException 
*/
public boolean copyFileAtFtp(String realPath,String filetempl, String path) throws Exception {
if(ftp==null || !ftp.isConnected()){
connect();
}
//System.out.println("COPY:"+path);
String dir=StringUtils.substringBeforeLast(path, "/");
String remoteFileName=StringUtils.substringAfterLast(path, "/");
if(!exists(dir)){
createDirectory(dir);
}
File f=new File(realPath+dir);
if(!f.exists()){
f.mkdirs();
}
String tempPath=realPath + path;
System.out.println(tempPath);//  /History/吴忠/   /Useing/
System.out.println(filetempl);//1234.zip
System.out.println(dir+"/");// /Useing/
System.out.println(remoteFileName);//吴忠
this.download(tempPath, filetempl);
this.upload(tempPath, remoteFileName, "/"+dir+"/");
return true;
}
}

0 0
原创粉丝点击