使用java对ftp进行文件的上传下载demo

本文引用了https://www.cnblogs.com/lr393993507/p/5502266.html资源,并做了一些优化

 

这里有个写好的java项目demo,csdn好像擅自给我的资源加了很多积分,我原来只设置2个,现在要7个,下面是资源的地址,如果不能用,请留言:

https://pan.baidu.com/s/11DcCCdgPQKnTIg6Bhvp7Yg      ek6i 
 

同时附csdn的资源地址:https://download.youkuaiyun.com/download/qq_30307137/10513665

所需jar:

ftp model类,负责ftp连接属性的设置, 提供set get 方法:

package com.ftp.model;


public class Ftp {
private String ipAddr;//ip地址
    
    private Integer port;//端口号
    
    private String userName;//用户名
    
    private String pwd;//密码
    
    private String path;//路径
    
    public Ftp(String ipAddr, Integer port, String userName, String pwd,
String path) {

this.ipAddr = ipAddr;
this.port = port;
this.userName = userName;
this.pwd = pwd;
this.path = path;
}
    

public Ftp() {

}

public String getIpAddr() {
        return ipAddr;
    }

    public void setIpAddr(String ipAddr) {
        this.ipAddr = ipAddr;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;

    }

    public String getUserName() {
        return userName;

    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
 

}

ftp进行上传下载的工具类:

package com.ftp.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;


import com.ftp.model.Ftp;


public class FtpUtils {

private static Logger logger=Logger.getLogger(FtpUtils.class);
private static FTPClient ftp;
/**
     * 获取ftp连接
     * @param f
     * @return
     * @throws Exception
     */
    public static boolean connectFtp(Ftp f) throws Exception{
        ftp=new FTPClient();
        boolean flag=false;
        int reply;
        if (f.getPort()==null) {
            ftp.connect(f.getIpAddr(),21);
        }else{
            ftp.connect(f.getIpAddr(),f.getPort());
        }
        ftp.login(f.getUserName(), f.getPwd());
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();      
        if (!FTPReply.isPositiveCompletion(reply)) {      
              ftp.disconnect();      
              return flag;      
        }      
        ftp.changeWorkingDirectory(f.getPath());      
        flag = true;   
       
        return flag;
    }
   
    public static void closeFtp(){
        if (ftp!=null && ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void upload(File f) throws Exception{
        if (f.isDirectory()) {
            ftp.makeDirectory(f.getName());
            ftp.changeWorkingDirectory(f.getName());
            String[] files=f.list();
            for(String fstr : files){
                File file1=new File(f.getPath()+"/"+fstr);
                if (file1.isDirectory()) {
                    upload(file1);
                    ftp.changeToParentDirectory();
                }else{
                    File file2=new File(f.getPath()+"/"+fstr);
                    FileInputStream input=new FileInputStream(file2);
                    ftp.storeFile(file2.getName(),input);
                    input.close();
                }
            }
        }else{
            File file2=new File(f.getPath());
            FileInputStream input=new FileInputStream(file2);
            ftp.storeFile(file2.getName(),input);
            input.close();
        }
    }
    
    /**
     * 下载链接配置
     * @param f
     * @param localBaseDir 本地目录
     * @param remoteBaseDir 远程目录
     * @throws Exception
     */
    public static void startDown(Ftp f,String localBaseDir,String remoteBaseDir,String alone ) throws Exception{
        if (FtpUtils.connectFtp(f)) {
            try { 
                FTPFile[] files = null; 
                boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); 
                if (changedir) { 
                    ftp.setControlEncoding("GBK"); 
                    files = ftp.listFiles(); 
                    
                    if(null!=alone&&!("".equals(alone))){
                    for(int i=0;i<files.length;i++){
                    if(files[i].getName().contains(alone)){
                    downloadFile(files[i], localBaseDir, remoteBaseDir); 
                    }
                    }
                    }else{
                    for (int i = 0; i < files.length; i++) { 
                    downloadFile(files[i], localBaseDir, remoteBaseDir); 
                    }
                    }
                } 
            } catch (Exception e) { 
                logger.error(e); 
                logger.error("下载过程中出现异常"); 
            } 
        }else{
            logger.error("链接失败!");
        }   
    }
    
    
    /** 
     * 
     * 下载FTP文件 
     * 当你需要下载FTP文件的时候,调用此方法 
     * 根据<b>获取的文件名,本地地址,远程地址</b>进行下载 
     * 
     * @param ftpFile 
     * @param relativeLocalPath 
     * @param relativeRemotePath 
     */ 
    private  static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) { 
        if (ftpFile.isFile()) {
            if (ftpFile.getName().indexOf("?") == -1) { 
                OutputStream outputStream = null; 
                try { 
                    File locaFile= new File(relativeLocalPath+ ftpFile.getName()); 
                    //判断文件是否存在,存在则返回 
                    if(locaFile.exists()){ 
                        return; 
                    }else{ 
                        outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName()); 
                        ftp.retrieveFile(ftpFile.getName(), outputStream); 
                        outputStream.flush(); 
                        outputStream.close(); 
                    } 
                } catch (Exception e) { 
                    logger.error(e);
                } finally { 
                    try { 
                        if (outputStream != null){ 
                            outputStream.close(); 
                        }
                    } catch (IOException e) { 
                       logger.error("输出文件流异常"); 
                    } 
                } 
            } 
        } else { 
            String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); 
            String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString()); 
            File fl = new File(newlocalRelatePath); 
            if (!fl.exists()) { 
                fl.mkdirs(); 
            } 
            try { 
                newlocalRelatePath = newlocalRelatePath + '/'; 
                newRemote = newRemote + "/"; 
                String currentWorkDir = ftpFile.getName().toString(); 
                boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); 
                if (changedir) { 
                    FTPFile[] files = null; 
                    files = ftp.listFiles(); 
                    for (int i = 0; i < files.length; i++) { 
                        downloadFile(files[i], newlocalRelatePath, newRemote); 
                    } 
                } 
                if (changedir){
                    ftp.changeToParentDirectory(); 
                } 
            } catch (Exception e) { 
                logger.error(e);
            } 
        } 
    } 
 

}

 

测试类:

package com.ftp.test;


import java.io.File;


import org.apache.commons.net.ftp.FTPFile;


import com.ftp.model.Ftp;
import com.ftp.utils.FtpUtils;


public class Test {
public static void main(String[] args) {
try {
Ftp ftp=new Ftp();
ftp.setIpAddr("127.0.0.1");//直接写ip地址,不需要加ftp://
ftp.setPath("/haha");      //你需要下载上传或下载文件的ftp路径
ftp.setPort(21);           //端口号
ftp.setPwd("123456");      //ftp密码
ftp.setUserName("admin");  //ftp账号
FtpUtils.connectFtp(ftp); //连接

//上传方法的调用:将本地桌面文件heihei.txt上传到ftp上haha目录下
File f=new File("C:\\Users\\Administrator\\Desktop\\heihei.txt");//需要上传文件的路径+文件名
FtpUtils.upload(f);      //执行上传
 
//下载方法的调用:将ftp上目录为haha中的xu2.xlsx文件下载到桌面,如果需要下载haha中的全部文件,则第四个参数为null
//FtpUtils.startDown(ftp, "C:\\Users\\Administrator\\Desktop\\", null,"xu2.xlsx");
/*
* 下载方法说明:FtpUtils.startDown(ftp, "C:\\Users\\Administrator\\Desktop\\", null,"xu2.xlsx");
* 下载ftp上目录为haha中xu2.xlsx文件到桌面。

* FtpUtils.startDown(ftp, "C:\\Users\\Administrator\\Desktop\\", null,null);
* 下载ftp上目录为haha下的所有文件到桌面。

* 如果你需要下载haha目录下的多个文件,但是又不需要全部下载,调用多次就行了,如下:
* FtpUtils.startDown(ftp, "C:\\Users\\Administrator\\Desktop\\", null,"xu1.xlsx");
* FtpUtils.startDown(ftp, "C:\\Users\\Administrator\\Desktop\\", null,"xu2.xlsx");
* FtpUtils.startDown(ftp, "C:\\Users\\Administrator\\Desktop\\", null,"xu3.xlsx");

* 注意:只要 ftp.setPath("/haha")方法参数设置好,下载方法第三个参数方法最好是null


* 如果发现上传下载出现问题,尝试从以下入手:
* 1.ftp上打开该用户的上传下载权限
* 2.检查路经是否写错了
* 3.无论上传下载,文件名不能包含中文、空格,最好英文、数字. ---------(这条很重要)----------
*/



} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();

}

}

 

}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值