利用Java 代码创建ftp客户端并实现上传下载等功能

由于公司的项目需要,现在需要搭建一个ftp的客户端,所以在查看别人代码后,根据其代码写出ftp客户端,并修改其中的代码,实现上传后的文件名与需要上传的文件名一致,供以后查看文件时方便。先贴出代码;


package com.demo;

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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;

/**
 * ftp客户端,实现文件的上传,下载,等功能
 * Created by T430 on 2017/5/9.
 */
public class FtpTest  {
    private FTPClient client;

    public FtpTest(String host,int port ,String username,  String password) throws IOException {
        initFtpClient(host, port, username, password);
    }
    public FtpTest(String host, String userName, String password)
            throws SocketException, IOException {
        initFtpClient(host, 21, userName, password);
    }

    /**
     * 登录
     * @param host
     * @param port
     * @param userName
     * @param password
     * @throws IOException
     */
    public void initFtpClient(String host, int port, String userName,
                              String password) throws IOException {

        client =new FTPClient();//s生成一个新的client
        client.connect(host,port);//链接
        client.login(userName,password);//通过用户名和密码登录
    }

    /**
     * 得到所有目录
     * @param remotepath
     * @return
     */
    public FTPFile[] listFiles(String remotepath) throws IOException {
        if (client == null){
            return null;
        }
        client.changeWorkingDirectory(remotepath);//获取所有的目录
        return client.listFiles();//返回获取到的目录信息
    }

    /**
     * 上传
     * @param localpath(本地路径)
     * @param remotepath(ftp的路径)
     * @return上传是否成功
     * @throws FileNotFoundException
     */
    public boolean upload(String localpath,String remotepath) throws IOException {
        if (null == client){//如果获取到的信息为空则返回false
            return false;
        }
        boolean res= false;
        FileInputStream fis= new FileInputStream(localpath);
        int index= remotepath.lastIndexOf("/");//获取路径的最后一个斜杠位置

        ///把上传的文件名改为原文件名//
        int  filenameplace= localpath.lastIndexOf(".");//获取上传文件类型中'.'的位置

        String filename= localpath.substring(localpath.lastIndexOf("\\")+1,filenameplace);//获取原路径的文件名

        String fileType= localpath.substring(filenameplace);//获取源文件的类型
        
        if (-1 != index){//如果不是最后的位置,则表明成功上传
            client.setFileType(FTPClient.BINARY_FILE_TYPE);//设置上传文件的类型

            client.changeWorkingDirectory(remotepath.substring(0,index));//获取上传的路径地址
         
            //修改上传的文件名,保持上传后文件名一致
            res=client.storeFile(filename+fileType,fis);
        }
        fis.close();//关闭流
        return res;
    }

    /**
     * 下载
     * @param remotepath ftp路径
     * @param localpath 本地路径
     * @return 下载是否成功
     */
    public boolean downLoad(String remotepath, String localpath) throws IOException {
        boolean res= false;
        if (null == client){//如果获取的为空 则返回FALSE
            return res;
        }

        FileOutputStream fos= new FileOutputStream(localpath);//下载到本地路径

        res=client.retrieveFile(remotepath,fos);

        fos.flush();//清楚缓存
        fos.close();//关闭流
        return res;
    }

    /**
     * 删除文件
     * @param remotepath ftp服务端路径
     * @return
     */
    public boolean delete(String remotepath) throws IOException {
        boolean res= false;

        if (null == client){
            return res;
        }

        return  client.deleteFile(remotepath) || deleteDirectory(remotepath);//删除文件是否成功
    }

    /**
     * 创建目录
     * @param remotepath ftp服务端路径
     * @return
     */
    public boolean makeDirectory(String remotepath) throws IOException {
        boolean res = false;

        if (null == client){
            return res;
        }

        String[] item = remotepath.split("/");//以‘/’分割成字符串数组
        String currentPath="";
        for (int i = 0; i <item.length-1 ; i++) {

            currentPath = currentPath +"/"+item[i];//创建目录
            client.makeDirectory(currentPath);
        }
        return client.makeDirectory(remotepath);
    }

    /**
     * 删除文件
     * @param remotepath ftp端路径
     * @return
     */
    private boolean deleteDirectory(String remotepath) throws IOException {
        boolean res= false;
        FTPFile[] files= listFiles(remotepath);//获取文件数组
        for (int i = 0; i <files.length ; i++) {
            if (files[i].isDirectory()){ //如果是删除目录
                    deleteDirectory(remotepath+"/"+files[i].getName());//删除目录
            }else {
               client.deleteFile(remotepath+"/"+files[i].getName());//删除文件
            }

        }
        return client.removeDirectory(remotepath);
    }

    /**
     * 重命名
     * @param remoteOldPath ftp旧名字文件
     * @param remoteNewPath ftp新名字文件
     * @return 是否修改名字成功
     */
    public boolean replaceName(String remoteOldPath,String remoteNewPath) throws IOException {

        if (null == client){
            return false;
        }
        return client.rename(remoteOldPath,remoteNewPath);
    }

    /**
     * 退出登录
     * @throws IOException
     */
    public void close() throws IOException {
        if (null != client)
            client.logout();
    }

    public static void main (String[] args) throws IOException {
            FtpTest ft= new FtpTest("虚拟机路径",21,"设定的用户名","设定的密码");
       //   System.out.print( ft.upload("D:\\7za.exe","/ftp"));
          FTPFile[] files=ft.listFiles("/ftp");
        for (int i = 0; i <files.length ; i++) {
            System.out.println("内容有:"+files[i].getName());
        }
        System.out.println("删除文件:"+ft.delete("222.png"));
    }
}


在这里非常感谢 @李跃东, 把他的帖子贴出来,供大家学习。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值