java实现ftp文件的下载,删除

package hboa.modules.data.impls;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

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

import xsf.resource.ResourceManager;

public class FtpUtils {
    private static Log logger = LogFactory.getLog(FTPClient.class);

    private FTPClient ftp;// ftp对象
    private String ip; // 需要连接到的ftp端的ip
    private int port; // 连接端口,默认21
    private String name; // 要连接到的ftp端的名字
    private String pwd; // 要连接到的ftp端的对应得密码

    /*
     * 调用此方法,输入对应得 ip,端口, 要连接到的ftp端的名字, 要连接到的ftp端的对应得密码。 连接到ftp对象,并验证登录进入ftp
     */
    public FtpUtils(String ip, int port, String name, String pwd){
        String filePath = ResourceManager.getAppKey("FTPPATH", "");
        ftp = new FTPClient();
        this.ip = ip;
        this.port = port;
        this.name = name;
        this.pwd = pwd; // 验证登录
        try {
            ftp.connect(ip, port);
            System.out.println(ftp.login(name, pwd));
            ftp.setCharset(Charset.forName("UTF-8"));
            ftp.setControlEncoding("UTF-8");
            FTPFile[] fs = ftp.listFiles();
            
            System.out.println(fs.length);
            
            for (FTPFile file : fs) {
                String fileName = file.getName();
                //下载文件
                this.download(fileName, fileName);
                //删除ftp文件
                this.deleteFile(filePath, fileName);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            //判断是否曾经链接成功过
             if(ftp.isConnected()){
               try{
                   //退出登录
                   ftp.logout();
               }catch(IOException e){
                   e.printStackTrace();
               }
           }
            
        }
    }

    public void downloadFile() {

        InputStream is = null;
        FileOutputStream fos = null;
        try {
            FTPFile[] fs = ftp.listFiles();
            
            System.out.println(fs.length);
            
            for (FTPFile file : fs) {
                String fileName = file.getName();
                //ftp.enterLocalPassiveMode();
                
                System.out.println(fileName);
                
                is = ftp.retrieveFileStream(fileName);

                //输出路径的话,可以直接读resource中配置的导入路径,直接下载到那个路径下。
                String path = ResourceManager.getAppKey("EXPADRRESS", "");
                fos = new FileOutputStream(new File(path+"/"+fileName));
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = is.read(b)) > 0) {
                    fos.write(b, 0, len);
                }
                fos.flush();
                ftp.dele(fileName);
                
                if (is != null) {
                    is.close();
                }
                ftp.completePendingCommand();
                ftp.enterLocalPassiveMode();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
                
                ftp.logout();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
     /**
     * 从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;  
        }  
 
        // 设置被动模式  
        ftp.enterLocalPassiveMode();  
        // 设置以二进制方式传输  
        ftp.setFileType(FTP.BINARY_FILE_TYPE);  
 
        if (ftp.listFiles(new String(pathname.getBytes(),ftp.getControlEncoding())).length == 0) {  
            logger.fatal("下载文件不存在");  
            throw new Exception("下载文件不存在");  
        }  
      //输出路径的话,可以直接读resource中配置的导入路径,直接下载到那个路径下。
        String path = ResourceManager.getAppKey("EXPADRRESS", "");
        File tmp = new File(filename + "_tmp"); // 临时文件  
        File file = new File(path+"/"+filename);  
        FileOutputStream output = null;  
        boolean flag;  
        try {  
            output = new FileOutputStream(tmp);  
            flag = ftp.retrieveFile(new String(pathname.getBytes(),ftp.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;  
    }  
    /** * 删除文件 *
     * @param pathname FTP服务器保存目录 *
     * @param filename 要删除的文件名称 *
     * @return */
     public boolean deleteFile(String pathname, String filename){
         boolean flag = false;
         try {
             System.out.println("开始删除文件");
             //切换FTP目录
             ftp.changeWorkingDirectory(pathname);
             ftp.dele(filename);
             flag = true;
             System.out.println("删除文件成功");
         } catch (Exception e) {
             System.out.println("删除文件失败");
             e.printStackTrace();
         }
         return flag;
     }

    public static void main(String args[]) throws Exception {
        String ip = "192.168.1.192";  //ip
        int port = 22;  //端口
        String username = "anonymous"; //用户名,内网,这里用匿名登录。
        String password = "";
        FtpUtils m = new FtpUtils(ip, port, username, password);
//        m.downloadFile();
    }
}

jar包:commons-net-3.3

posted @ 2019-02-21 16:22  诡哑  阅读(284)  评论(0)    收藏  举报