最全的ftp 操作工具(所有方法经过测试,附ftp 服务配置)

1、前言

ftp 配置详解,参照前面的博文,这里有一份例子是关于配置在数据库的

http://download.csdn.net/detail/ice_grey/8525957

2、ftp 操作工具类

自己个人开发用到的,网上有许多,代码部分来源网上,但好象都有路径中文问题,或者其他问题,自己修改了一下,并测试通过

2.1

package cn.sinobest.ypgj.netdisk.util;

public class FTPModel {

	private String ftpId;

	private String username;

	private String password;

	private String url;

	private int port;

	private String remoteDir;

	public FTPModel() {

	}

	public FTPModel(String username, String password, String url, int port,
                    String remoteDir) {
		this.username = username;
		this.password = password;
		this.url = url;
		this.port = port;
		this.remoteDir = remoteDir;
	}

    public String getFtpId() {
        return ftpId;
    }

    public void setFtpId(String ftpId) {
        this.ftpId = ftpId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getRemoteDir() {
        return remoteDir;
    }

    public void setRemoteDir(String remoteDir) {
        this.remoteDir = remoteDir;
    }
}

2.2

package cn.sinobest.ypgj.netdisk.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

/**
 * Apache.FTPClient FTP操作共公类
 * 
 * @author
 * 
 */
public class FTPCommon {
	private FTPClient ftpClient;

	private FTPModel ftpModel;
    private static String LOCAL_CHARSET = "GBK";// FTP协议里面,规定文件名编码为iso-8859-1private static String SERVER_CHARSET = "ISO-8859-1";
    private static final String ROOT = "/";

	public FTPCommon(FTPModel ftp) {
        super();
		// 从配置文件中读取初始化信息
		this.ftpClient = new FTPClient();
		this.ftpModel = ftp;

	}

	/**
	 * 连接并登录FTP服务器
	 * 
	 */
	public boolean ftpLogin() throws IOException {
		boolean isLogin = false;
		FTPClientConfig ftpClientConfig = new FTPClientConfig(
				FTPClientConfig.SYST_NT);
		ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
		this.ftpClient.setControlEncoding("UTF-8");
//        ftpClient.enterLocalPassiveMode();
        this.ftpClient.configure(ftpClientConfig);

		try {
			if (this.ftpModel.getPort() > 0) {
				this.ftpClient.connect(ftpModel.getUrl(), ftpModel.getPort());
			} else {
				this.ftpClient.connect(ftpModel.getUrl());
			}
			// FTP服务器连接回答
			int reply = this.ftpClient.getReplyCode();
//            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
//                LOCAL_CHARSET = "UTF-8";
//            }
			if (!FTPReply.isPositiveCompletion(reply)) {
				this.ftpClient.disconnect();
				return isLogin;
			}
            isLogin = this.ftpClient.login(this.ftpModel.getUsername(), this.ftpModel
					.getPassword());
			this.ftpClient.changeWorkingDirectory(this.ftpModel.getRemoteDir());
			this.ftpClient.setFileType(FTPClient.FILE_STRUCTURE);

//			LogUtil.infoOutPut("成功登陆FTP服务器:" + this.ftpModel.getUrl() + " 端口号:"
//					+ this.getFtpModel().getPort() + " 目录:"
//					+ this.ftpModel.getRemoteDir());

		} catch (SocketException e) {
			e.printStackTrace();
//			LogUtil.logPrint("连接FTP服务失败!", Constants.LOG_EXCEPTION);
//			LogUtil.logPrint(e.getMessage(), Constants.LOG_EXCEPTION);
		} catch (IOException e) {
			e.printStackTrace();
            System.out.println("登录FTP服务失败!");
//			LogUtil.logPrint("登录FTP服务失败!", Constants.LOG_EXCEPTION);
//			LogUtil.logPrint(e.getMessage(), Constants.LOG_EXCEPTION);
		}
        if(isLogin){
                        System.out.println("成功登陆FTP服务器:" + this.ftpModel.getUrl() + " 端口号:"
					+ this.getFtpModel().getPort() + " 目录:"
					+ this.ftpModel.getRemoteDir());
        }
		System.out.println(this.ftpClient.getBufferSize());
		this.ftpClient.setBufferSize(1024 * 2);
		this.ftpClient.setDataTimeout(2000);
		return isLogin;
	}

	/**
	 * 退出并关闭FTP连接
	 * 
	 */
	public void close() {
		if (null != this.ftpClient && this.ftpClient.isConnected()) {
			try {
				boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
				if (reuslt) {
                    System.out.println("退出并关闭FTP服务器的连接");
				}
			} catch (IOException e) {
				e.printStackTrace();
                System.out.println("退出FTP服务器异常!");
//				LogUtil.exception(e.getMessage());
			} finally {
				try {
					this.ftpClient.disconnect();// 关闭FTP服务器的连接
				} catch (IOException e) {
					e.printStackTrace();
                    System.out.println("关闭FTP服务器的连接异常!");
//					LogUtil.exception(e.getMessage());
				}
			}
		}
	}

	/**
	 * 检查FTP服务器是否关闭 ,如果关闭接则连接登录FTP
	 * 
	 * @return
	 */
	public boolean isOpenFTPConnection() {
        long time  = System.currentTimeMillis();
		boolean isOpen = false;
		if (null == this.ftpClient) {
			return false;
		}
		try {
			// 没有连接
			if (!this.ftpClient.isConnected()) {
				isOpen = this.ftpLogin();
			}
		} catch (Exception e) {
			e.printStackTrace();
            System.out.println("FTP服务器连接登录异常!");
//			LogUtil.exception(e.getMessage());
			isOpen = false;
		}
        if(isOpen){
            System.out.println("===============登录成功!=============");
        }else{
            System.out.println("===============登录失败!==============");
        }
        System.out.println("耗时 "+(System.currentTimeMillis()-time));
		return isOpen;
	}

	/**
	 * 设置传输文件的类型[文本文件或者二进制文件]
	 * 
	 * @param fileType--FTPClient.BINARY_FILE_TYPE,FTPClient.ASCII_FILE_TYPE
	 */
	public void setFileType(int fileType) {
		try {
			this.ftpClient.setFileType(fileType);
		} catch (IOException e) {
			e.printStackTrace();
//			LogUtil.exception("设置传输文件的类型异常!");
//			LogUtil.exception(e.getMessage());
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param localFilePath
	 *            本地文件名及路径
	 * @param remoteFileName
	 *            远程文件名称
	 * @return
	 */
	public boolean downloadFile(String localFilePath, String remoteFileName) {
        changeDir(ROOT);
        setFileType(FTPClient.BINARY_FILE_TYPE);
		BufferedOutputStream outStream = null;
		boolean success = false;
		try {
			outStream = new BufferedOutputStream(new FileOutputStream(
					localFilePath));
			success = this.ftpClient.retrieveFile(remoteFileName, outStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outStream != null) {
				try {
					outStream.flush();
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
        if(success)
            System.out.println("============== 下载文件成功===========");
        return success;
	}
	/**
	 * 下载文件
	 * @param remoteFileName
	 *            远程文件名称路径
	 * @return
	 */
	public InputStream webDownloadFile(String remoteFileName) {
        changeDir(ROOT);
        setFileType(FTPClient.BINARY_FILE_TYPE);
        InputStream inputStream = null;
		boolean success = false;
		try {
//			outStream = new BufferedOutputStream(new FileOutputStream(
//					localFilePath));
            inputStream = this.ftpClient.retrieveFileStream(remoteFileName);
            if(inputStream == null){
                System.err.println("ftp服务器没有该文件!");
                return null;
            }
        } catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
	}

	/**
	 * 下载文件
	 * 
	 * @param localFile
	 *            本地文件
	 * @param remoteFileName
	 *            远程文件名称
	 * @return
	 */
	public boolean downloadFile(File localFile, String remoteFileName) {
        changeDir(ROOT);
        setFileType(FTPClient.BINARY_FILE_TYPE);
		BufferedOutputStream outStream = null;
		FileOutputStream outStr = null;
		boolean success = false;
		try {
			outStr = new FileOutputStream(localFile);
			outStream = new BufferedOutputStream(outStr);
			success = this.ftpClient.retrieveFile(remoteFileName, outStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != outStream) {
					try {
						outStream.flush();
						outStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (null != outStr) {
					try {
						outStr.flush();
						outStr.close();
					} catch (IOException e) {
						e.printStackTrace();
					}

				}
			}
		}
		return success;
	}

	/**
	 * 上传文件
	 * 
	 * @param localFilePath
	 *            本地文件路径及名称
	 * @param remoteFileName
	 *            FTP 服务器文件名称
	 * @return
	 */
	public boolean uploadFile(String localFilePath, String remoteFileName) {
        changeDir(ROOT);
        //设置传输为二进制文件

        setFileType(FTPClient.BINARY_FILE_TYPE);
		BufferedInputStream inStream = null;
		boolean success = false;
		try {
			inStream = new BufferedInputStream(new FileInputStream(
					localFilePath));
			success = this.ftpClient.storeFile(remoteFileName, inStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
        if(success)
            System.out.println("============== 上传文件成功===========");
        else
            System.out.println("============== 上传文件失败===========");
        return success;
	}
	/**
	 * 上传文件
	 *
	 * @param file
	 *            本地文件路径及名称
	 * @param remoteFileName
	 *            FTP 服务器文件目录
	 * @return
	 */
	public boolean uploadFile(MultipartFile file, String remoteFileName) {
        changeDir(ROOT);
        //设置传输为二进制文件
        setFileType(FTPClient.BINARY_FILE_TYPE);
		BufferedInputStream inStream = null;
		boolean success = false;
		try {
			inStream = new BufferedInputStream(file.getInputStream());
			success = this.ftpClient.storeFile(remoteFileName+"/"+file.getOriginalFilename(), inStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
        if(success)
            System.out.println("============== 上传文件成功===========");
        else
            System.out.println("============== 上传文件失败===========");
        return success;
	}

	/**
	 * 上传文件
	 * 
	 * @param localFile
	 *            本地文件
	 * @param remoteFileName
	 *            FTP 服务器文件名称
	 * @return
	 */
	public boolean uploadFile(File localFile, String remoteFileName) {
        changeDir(ROOT);
        //设置传输为二进制文件
        setFileType(FTPClient.BINARY_FILE_TYPE);
		BufferedInputStream inStream = null;
		boolean success = false;
		try {
			inStream = new BufferedInputStream(new FileInputStream(localFile));
			success = this.ftpClient.storeFile(remoteFileName, inStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
        if(success)
            System.out.println("============== 上传文件成功===========");
        else
            System.out.println("============== 上传文件失败===========");
		return success;
	}
	/**
	 * 上传文件
	 *
	 * @param inputStream
	 *            本地文件
	 * @param remoteFileName
	 *            FTP 服务器文件名称
	 * @return
	 */
	public boolean uploadFile(InputStream inputStream, String remoteFileName) {
        changeDir(ROOT);
        //设置传输为二进制文件
        setFileType(FTPClient.BINARY_FILE_TYPE);
		BufferedInputStream inStream = null;
		boolean success = false;
		try {
			inStream = new BufferedInputStream(inputStream);
			success = this.ftpClient.storeFile(remoteFileName, inStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
        if(success)
            System.out.println("============== 上传文件成功===========");
        else
            System.out.println("============== 上传文件失败===========");
		return success;
	}


    /**
     * 在服务器上创建目录
     * @param pathName
     * @return
     * @throws IOException
     */
    public boolean createDirectory(String pathName) throws IOException {
        return ftpClient.makeDirectory(pathName);
    }
    /**
     * 在服务器上递归创建目录
     * @param dirPath
     * @return
     * @throws IOException
     */
    public boolean createDirectorys(String dirPath) throws IOException {
        boolean status = true;
        String directory = dirPath.substring(0, dirPath.lastIndexOf("/")+1);
        ftpClient.makeDirectory(ROOT);
//        if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(directory)){
//        System.out.println(existDirectory(dirPath));
        if(!existDirectory(dirPath)){
//        if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))){
            //如果远程目录不存在,则递归创建远程服务器目录
            System.out.println("in------");
            int start=0;
            int end = 0;
            if(directory.startsWith("/")){
                start = 1;
            }else{
                start = 0;
            }
            end = directory.indexOf("/",start);
            while(true){
                String subDirectory = new String(dirPath.substring(start, end));
//                String subDirectory = new String(dirPath.substring(start,end).getBytes("GBK"),"iso-8859-1");
                if(!ftpClient.changeWorkingDirectory(subDirectory)){
                    if(ftpClient.makeDirectory(subDirectory)){
                        ftpClient.changeWorkingDirectory(subDirectory);
                    }else {
                        System.out.println("创建目录失败");
                        return false;
                    }
                }

                start = end + 1;
                end = directory.indexOf("/",start);

                //检查所有目录是否创建完毕
                if(end <= start){
                    break;
                }
            }
        }
        return status;
    }

    /**
     * 在服务器上删除目录
     * @param path
     * @return
     * @throws IOException
     */
    public boolean removeDirectory(String path) throws IOException {
        return ftpClient.removeDirectory(path);
    }

    /**
	 * 变更工作目录
	 * 
	 * @param remoteDir--目录路径
	 */
	public boolean changeDir(String remoteDir) {
        boolean flag = false;

		try {
			flag = this.ftpClient.changeWorkingDirectory(remoteDir);
//            System.out.println("变更工作目录为:" + remoteDir);
		} catch (IOException e) {
            flag = false;
			e.printStackTrace();
            System.out.println("变更工作目录为:" + remoteDir + "时出错!");
//			LogUtil.exception(e.getMessage());
		}
        return flag;

	}

    /**
     * 删除所有文件和目录
     * @param path
     * @param isAll true:删除所有文件和目录
     * @return
     * @throws IOException
     */
    public boolean removeDirectory(String path, boolean isAll)
            throws IOException {

        if (!isAll) {
            return removeDirectory(path);
        }

        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr == null || ftpFileArr.length == 0) {
            return removeDirectory(path);
        }
        //
        for (FTPFile ftpFile : ftpFileArr) {
            String name = ftpFile.getName();
            if (ftpFile.isDirectory()) {
                System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");
                removeDirectory(path + "/" + name, true);
            } else if (ftpFile.isFile()) {
                System.out.println("* [sF]Delete file ["+path + "/" + name+"]");
                deleteFile(path + "/" + name);
            } else if (ftpFile.isSymbolicLink()) {

            } else if (ftpFile.isUnknown()) {

            }
        }
        return ftpClient.removeDirectory(path);
    }

    /**
     * 检查目录在服务器上是否存在 true:存在  false:不存在
     * @param path
     * @return
     * @throws IOException
     */
    public boolean existDirectory(String path) throws IOException {
//        System.out.println("path-------------------"+path);
        boolean flag = false;
        try {
                changeDir(ROOT);
//            System.out.println("回到根目录:" + ftpClient.changeWorkingDirectory("/"));
//        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
//        System.out.println(ftpFileArr.length);
//            flag = false;
//            ftpClient.makeDirectory(this.ftpModel.getRemoteDir());
            if(ftpClient.changeWorkingDirectory(path)){
                flag = true;
            }
        } catch (IOException e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除服务器上的文件
     * @param pathName
     * @return
     * @throws IOException
     */
    public boolean deleteFile(String pathName) throws IOException {
        changeDir(ROOT);
        boolean flag = ftpClient.deleteFile(pathName);
        if(flag)
            System.out.println("============== 成功删除文件==========="+pathName);
        return flag;
    }

    /**
	 * 变更工作目录
	 * 
	 * @param remoteDirs--目录路径
	 */
	public void changeDir(String[] remoteDirs) {
		String dir = "";
		try {
			for (int i = 0; i < remoteDirs.length; i++) {
				this.ftpClient.changeWorkingDirectory(remoteDirs[i]);
				dir = dir + remoteDirs[i] + "/";
			}
            System.out.println("变更工作目录为:" + dir);
		} catch (IOException e) {
			e.printStackTrace();
            System.out.println("变更工作目录为:" + dir + "时出错!");
//			LogUtil.exception(e.getMessage());
		}

	}

	/**
	 * 返回上级目录
	 * 
	 */
	public void toParentDir(String[] remoteDirs) {
		try {
			for (int i = 0; i < remoteDirs.length; i++) {
				this.ftpClient.changeToParentDirectory();
			}
//			LogUtil.info("返回上级目录");
		} catch (IOException e) {
			e.printStackTrace();
//			LogUtil.exception("返回上级目录时出错!");
//			LogUtil.exception(e.getMessage());
		}
	}

//    public String encode(String instr){
//        String newStr = "";
//        try {
//            byte[] bytes = instr.getBytes();
//            newStr = new String(bytes,"utf-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.println(newStr);
//        return newStr;
//    }
//
//    public String decode(String instr){
//        String newStr = "";
//        try {
//            byte[] bytes = instr.getBytes("UTF-8");
//            newStr = new String(bytes,"UTF-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return newStr;
//    }



	/**
	 * 返回上级目录
	 * 
	 */
	public void toParentDir() {
		try {
			this.ftpClient.changeToParentDirectory();
//			LogUtil.info("返回上级目录");
		} catch (IOException e) {
			e.printStackTrace();
//			LogUtil.exception("返回上级目录时出错!");
//			LogUtil.exception(e.getMessage());
		}
	}

	/**
	 * 获得FTP 服务器下所有的文件名列表
	 * 
	 * @param
	 * @return
	 */
	public List getFileLists() {
        changeDir("/");
		String files[] = null;
        List retList = new ArrayList();
		try {
			files = this.ftpClient.listNames();
            for(int i = 0; i getFileLists(String path) throws IOException {
        changeDir(path);
        FTPFile[] ftpFiles= ftpClient.listFiles(path);
        //通过FTPFileFilter遍历只获得文件
/*      FTPFile[] ftpFiles2= ftpClient.listFiles(path,new FTPFileFilter() {
      @Override
      public boolean accept(FTPFile ftpFile) {
        return ftpFile.isFile();
      }
    });  */
        List retList = new ArrayList();
        if (ftpFiles == null || ftpFiles.length == 0) {
            return retList;
        }
        for (FTPFile ftpFile : ftpFiles) {
            if (ftpFile.isFile()) {
                retList.add(ftpFile.getName());
            }
        }
        return retList;
    }


    public FTPClient getFtpClient() {
		return ftpClient;
	}

	public FTPModel getFtpModel() {
		return ftpModel;
	}

	public void setFtpModel(FTPModel ftpModel) {
		this.ftpModel = ftpModel;
	}

    //only for test
    public static void main(String[] args) throws IOException {
        FTPModel ftpModel1 = new FTPModel("admin","123456","localhost",2121,"./res/home");
        FTPCommon ftpCommon = new FTPCommon(ftpModel1);
        ftpCommon.isOpenFTPConnection();
//        boolean flag = ftpCommon.existDirectory("我爱你");
//        System.out.println(File.separator);
        String name="开发用户/2015-03/";
//        name=new String(name.getBytes(LOCAL_CHARSET),"iso-8859-1");
        System.out.println("目录存在?"+ftpCommon.existDirectory(name));
        ftpCommon.createDirectorys(name);
//        ftpCommon.changeDir("我");

//        System.out.println(Arrays.asList(ftpCommon.getFileLists()));
//        System.out.println(ftpCommon.deleteFile(name + "/hai.txt"));
//        ftpCommon.removeDirectory("我",true);
//        System.out.println(flag);
//        String path = "";
//        ftpCommon.close();
//        ftpCommon.ftpLogin();
//        System.out.println(ftpCommon.uploadFile("h:\\123.jpg", name + "1111111.jpg"));
        System.out.println(ftpCommon.deleteFile( name + "1111111.jpg"));
//        System.out.println(ftpCommon.downloadFile("H://琥.xls", "日期.xls"));



    }

}


有bug请留言 !


你可能感兴趣的:(最全的ftp 操作工具(所有方法经过测试,附ftp 服务配置))