Java 实现FTP自动上传下载功能《一》

对于ftp自动上传下载,其中还会有删除,创建目录等,ftp上传是一个非常好用的常用的协议,在网上基本已经有了很多很多的内容包括工具类,在网上也看了好多前辈的文章等等,是一个非常简单实用的东西呢,有些人的ftp上会用两个jar包,我不知道区别在哪里,在自己写了一个ftpUtil之后,也就用到了一个jar,具体代码是这样的。

新手小白,ftp的知识点也是还有很多的,我也就只测试过上传感觉还是蛮快的,各位前辈看见那里有什么不如意的地方请指点。吐舌头

下一篇,win7上ftp服务的搭建

jar:commons-net-3.3.jar

package com.airchina.group.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

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.FTPReply;


/** 
 * FTP Client工具类
 */  
public class FTPClientUtil {  
  
    private static Log logger = LogFactory.getLog(FTPClient.class);
    
    private FTPClient ftpclient;  
    
//    public void task(){
//    	DateUtil.fullFormatCurrentTime();
//    }
  
    public FTPClientUtil(String host, int port) throws Exception {  
        this(host, port, null, null);  
    }  
  
    public FTPClientUtil(String host, int port, String username, String password)
            throws Exception {
        ftpclient = new FTPClient();
        try {
            ftpclient.connect(host, port);
            int reply = ftpclient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpclient.disconnect();
                logger.fatal("FTP服务器拒绝连接");
                throw new Exception("FTP服务器拒绝连接");
            }
            if (username != null) {
                if (!ftpclient.login(username, password)) {
                    ftpclient.disconnect();
                    logger.fatal("登陆验证失败,请检查账号和密码是否正确");
                    throw new Exception("登陆验证失败,请检查账号和密码是否正确");
                }
                ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
            }
        } catch (SocketException e) {
            logger.fatal("无法连接至指定FTP服务器", e);
            throw new Exception(e);
        } catch (IOException e) {
            logger.fatal("无法用指定用户名和密码连接至指定FTP服务器", e);
            throw new Exception(e);
        }  
    }  
  
    /** 
     *  
     * @param path 文件在FTP上存储的绝路径 
     * @param input 上传文 
     * @throws IOException 
     */  
    public boolean upload(String pathname, InputStream input)  
            throws IOException {  
        // 是否是在根目录 下  
        ftpclient.setFileType(FTP.BINARY_FILE_TYPE);  
        if (pathname.indexOf("/") != -1) {  
            String path = pathname.substring(0, pathname.lastIndexOf("/"));  
            mkdir(path);  
        }  
        return ftpclient.storeFile(new String(pathname.getBytes(), ftpclient.getControlEncoding()), input);  
    }  
  
    /** 
     * 从FTP服务器上下载指定的文件,命名为localName
     * @param pathname 
     * @param localName 
     * @return 
     * @throws Exception 
     */  
    public boolean download(String pathname, String localName) throws Exception {  
        String filename = localName != null ? localName : pathname  
                .substring(pathname.lastIndexOf("/") + 1);  
  
        if (filename == null || filename.isEmpty()) {  
            return false;  
        }  
  
        // 设置被动模式  
        ftpclient.enterLocalPassiveMode();  
        // 设置以二进制方式传输  
        ftpclient.setFileType(FTP.BINARY_FILE_TYPE);  
  
        if (ftpclient.listFiles(new String(pathname.getBytes(),ftpclient.getControlEncoding())).length == 0) {  
            logger.fatal("下载文件不存在");  
            throw new Exception("下载文件不存在");  
        }  
  
        File tmp = new File(filename + "_tmp"); // 临时文件  
        File file = new File(filename);  
        FileOutputStream output = null;  
        boolean flag;  
        try {  
            output = new FileOutputStream(tmp);  
            flag = ftpclient.retrieveFile(new String(pathname.getBytes(),ftpclient.getControlEncoding()), output);  
            output.close();  
            if (flag) {  
                // 下载成功,重命名临时文件。  
                tmp.renameTo(file);  
                System.out.println(file.getAbsolutePath());  
            }  
        } catch (FileNotFoundException e) {  
            logger.fatal("下载文件失败", e);  
            throw new Exception(e);  
        } finally {  
            output.close();  
        }  
  
        return flag;  
    }  
  
    /** 
     * 只删除文件,如果删除空目录请用如下方法: <code> 
     *  getFtpclient().removeDirectory(String pathname)  
     * </code> 参考 
     * {@link org.apache.commons.net.ftp.FTPClient FTPClient} 
     *  
     * @param pathname 
     * @return 成功删除返回true,否则返回false(如果文件不存在也返回false) 
     * @throws IOException 
     */  
    public boolean delete(String pathname) throws IOException {  
        return ftpclient.deleteFile(new String(pathname.getBytes(),ftpclient.getControlEncoding()));  
    }  
  
    /** 
     * 改变当前目录至pathname,"/"代表根目录 
     *  
     * @param pathname 
     *            路径名 
     * @return 如果改变成功返true否则返回false 
     * @throws IOException 
     */  
    public boolean changeWorkingDirectory(String pathname) throws IOException {  
        return ftpclient.changeWorkingDirectory(new String(pathname.getBytes(),ftpclient.getControlEncoding()));  
    }  
  
    /** 
     * @return {@link org.apache.commons.net.ftp.FTPClient FTPClient}对象 
     */  
    public FTPClient getFtpclient() {  
        return this.ftpclient;  
    }  
  
    /** 
     * @param ftpclient 
     *            {@link org.apache.commons.net.ftp.FTPClient FTPClient}对象 
     */  
    public void setFtpclient(FTPClient ftpclient) {  
        this.ftpclient = ftpclient;  
    }  
  
    public void close() throws Exception {  
        ftpclient.disconnect();  
    }  
  
    /** 
     *  
     * @param pathname 
     *            要创建的目录路径,可以是相对路径,也可以是绝路径("/"开始) 
     * @return 如果成功创建目录返回true,否则返回false(如果目录已存在也返回false) 
     * @throws IOException 
     */  
    public boolean mkdir(String pathname) throws IOException {
    	try{
    		ftpclient.setControlEncoding("ISO-8859-1");  
            //注意编码,如果不编码文件中文目录无法创建  
            return ftpclient.makeDirectory(new String(pathname.getBytes(),ftpclient.getControlEncoding()));	
    	}catch(Exception ex){
    		ex.printStackTrace();
    		return false;
    	}
          
    }  
  
}  

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值