FTPClient相关的链接、上传、下载、删除、转移文件、退出ftp操作

2 篇文章 0 订阅
package com.sh.cms.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

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

public class FtpUtil {
    private String path;

    private static FTPClient ftpClient;
    public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;
    public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;

    /**
     * 方法:connectServer 
     * 方法说明:    连接ftp服务器
     * @param      void
     * @return     FTPClient
    */
    public FTPClient connectServer() throws SocketException, IOException {
        ftpClient = new FTPClient();
        String ipAndPort = "";
        String ftpAddress = ftp地址;
        String startSub = ftpAddress.substring(0, ftpAddress.indexOf("@"));
        String endSub = ftpAddress.substring(ftpAddress.indexOf("@") + 1);
        String userPass = startSub.substring(startSub.lastIndexOf("/") + 1);
        String[] up = userPass.split(":");

        if (endSub.indexOf("/") != -1) {
            ipAndPort = endSub.substring(0, endSub.indexOf("/"));
            this.path = endSub.substring(endSub.indexOf("/") + 1);
        } else {
            ipAndPort = endSub;
        }
        String port;
        String ip;

        if (ipAndPort.contains(":")) {
            ip = ipAndPort.substring(0, ipAndPort.indexOf(":"));
            port = ipAndPort.substring(ipAndPort.indexOf(":") + 1);
        } else {
            ip = ipAndPort;
            port = "21";
        }
        connectServer(ip, Integer.parseInt(port), up[0], up[1]);
        return ftpClient;
    }

    /**
     * 方法:connectServer 
     * 方法说明:    连接ftp服务器
     * @param      void
     * @return     FTPClient
    */
    public FTPClient connectServer(String server, int port, String user,
            String password) throws SocketException, IOException {
        ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(3000);
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.connect(server, port);
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.login(user, password);
        } else {
            ftpClient.disconnect();
        }
        ftpClient.enterLocalPassiveMode();
        ftpClient.setBufferSize(1024);
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        return ftpClient;
    }


    /**
     * 方法:uploadxml
     * 方法说明:    向ftp服务器上传xml文件
     * @param      input:文件流,fileName:文件名称
     * @return     boolean
    */
    public boolean uploadxml(InputStream input, String fileName,
            String directory) throws Exception {
        if (StringUtil.isNotEmpty(this.path)) {
            directory = this.path + directory;
        }
        String[] s = directory.split("/");
        for (String p : s) {
            if (StringUtil.isNotEmpty(p)) {
                boolean staus = ftpClient.changeWorkingDirectory(p);
                if (!staus) {
                    ftpClient.makeDirectory(p);
                    ftpClient.changeWorkingDirectory(p);
                }
            }
        }

        boolean storeFile = ftpClient.storeFile(fileName, input);
        input.close();
        return storeFile;
    }


    /**
     * 方法:download
     * 方法说明:    从ftp服务器下载文件
     * @param      loadFileName:ftp上文件信息,saveFileName:保存的文件信息
     * @return     boolean
    */
    public boolean download(String loadFileName, String saveFileName)
            throws Exception {
        FileOutputStream fos = null;
        fos = new FileOutputStream(saveFileName);
        boolean ss = ftpClient.retrieveFile(loadFileName, fos);
        fos.close();
        return ss;

    }

    /**
     * 方法:moveFtpDir
     * 方法说明:    ftp服务器上文件迁移
     * @param      fromdir:当前文件目录,todir:要保存的目录
     * @return     boolean
    */
    public String moveFtpDir(String fromdir, String todir) {
        String ftpUrl = null;
        try {
            DateFormat df = new SimpleDateFormat("yyyyMMdd");
            String format = df.format(new Date());
            // 判断当前日期的文件夹是否存在
            if (todir != null && !"".equals(todir)) {
                FTPFile[] alldirs = ftpClient.listFiles("/");
                boolean flgdir = false;
                for (int i = 0; i < alldirs.length; i++) {
                    String dirname = alldirs[i].getName();
                    if (!dirname.equals(todir.substring(1))) {
                        continue;
                    } else {
                        flgdir = true;
                        break;
                    }
                }
                if (!flgdir) {
                    ftpClient.makeDirectory(todir + "/");
                }
                FTPFile[] allFile = ftpClient.listFiles(todir);
                boolean flg = false;
                for (int i = 0; i < allFile.length; i++) {
                    String dirname = allFile[i].getName();
                    if (!dirname.equals(format)) {
                        continue;
                    } else {
                        flg = true;
                        break;
                    }
                }
                if (!flg) {
                    ftpClient.makeDirectory(todir + "/" + format + "/");
                }
            }
            todir = todir + "/" + format + "/";
            // 移动文件
            if (fromdir != null && !"".equals(fromdir)) {
                FTPFile[] allFile = ftpClient.listFiles(fromdir);
                ftpClient
                        .makeDirectory(todir
                                + fromdir.substring(fromdir.lastIndexOf("/") + 1)
                                + "/");
                todir = todir + fromdir.substring(fromdir.lastIndexOf("/") + 1)
                        + "/";
                for (int i = 0; i < allFile.length; i++) {
                    String name = allFile[i].getName();
                    ftpClient.rename(fromdir + "/" + name, todir + "/" + name);
                }
                ftpClient.removeDirectory(fromdir);
                ftpUrl = todir.substring(0, todir.length() - 1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpUrl;
    }
    /**
      * 方法:moveFtpFileToDir 
      * 方法说明:    ftp移动文件到指定目录
      * @param fromdir 从这个文件路径
      * @param fileName 文件名称
      * @param todir  目标路径
      * @return
     */
    public String moveFtpFileToDir(String fromdir,String fileName, String todir) {
        String ftpUrl = null;
        try {
            // 移动文件
            if (StringUtil.isNotEmpty(fromdir)) {
                ftpClient.rename(fromdir + "/" + fileName, todir + "/" + fileName);
                ftpUrl = todir.substring(0, todir.length() - Constants.NUMBER_1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpUrl;
    }

    /**
     * 方法:downloadFile
     * 方法说明:    ftp服务器上下载文件
     * @param      remoteFileName:当前文件名称,localDires:要保存的目录,remoteDownLoadPath:ftp上文件目录
     * @return     boolean
    */
    public boolean downloadFile(String remoteFileName, String localDires,
            String remoteDownLoadPath) {
        String strFilePath = localDires + remoteFileName;
        BufferedOutputStream outStream = null;
        boolean success = false;
        try {
            ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            outStream = new BufferedOutputStream(new FileOutputStream(
                    strFilePath));
            success = ftpClient.retrieveFile(remoteFileName, outStream);
            if (success == true) {
                return success;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (success == false) {
        }
        return success;
    }


    /*** 
     * 将下载文件的输出流转为输入流 
     * @param remoteFileName   待下载文件名称 
     * @param remoteDownLoadPath remoteFileName所在的路径 
     * */

    public InputStream downloadMetadata(String remoteFileName,
            String remoteDownLoadPath) {
        InputStream in = null;
        try {
            ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            in = ftpClient.retrieveFileStream(remoteFileName);
            return in;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return in;
    }

    /*** 
     * @上传文件夹 
     * @param localDirectory 
     *            当地文件夹 
     * @param remoteDirectoryPath 
     *            Ftp 服务器路径 以目录"/"结束 
     * */
    public boolean uploadDirectory(String localDirectory,
            String remoteDirectoryPath) {
        File src = new File(localDirectory);
        try {
            ftpClient.makeDirectory(remoteDirectoryPath);

            File[] allFile = src.listFiles();
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    String srcName = allFile[currentFile].getPath().toString();
                    uploadFile(new File(srcName), remoteDirectoryPath);
                }
            }
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    // 递归
                    ftpClient.makeDirectory(remoteDirectoryPath + "/"
                            + allFile[currentFile].getName() + "/");
                    File src2 = new File(allFile[currentFile].getPath());
                    File[] allFile2 = src2.listFiles();
                    for (int currentFile2 = 0; currentFile2 < allFile2.length; currentFile2++) {
                        if (!allFile2[currentFile2].isDirectory()) {
                            uploadFile(new File(allFile2[currentFile2]
                                    .getPath().toString()), remoteDirectoryPath
                                    + "/" + allFile[currentFile].getName()
                                    + "/");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /*** 
     * 上传Ftp文件 
     * @param localFile 当地文件 
     * @param romotUpLoadePath上传服务器路径 - 应该以/结束 
     * */
    public boolean uploadFile(File localFile, String romotUpLoadePath) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            success = this.ftpClient.storeFile(localFile.getName(), inStream);
            if (success == true) {
                return success;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    /*** 
     * 上传CDN需要的XML文件 
     * @param tempftpDirectory 
     * @param filename文件名字 
     * @param r文件内容
     * */
    public boolean uploadCDNxmlFile(String filename, String r,
            String tempftpDirectory) {
        boolean success = false;
        InputStream is = null;
        try {
            // 1.输入流
            is = new ByteArrayInputStream(r.getBytes("utf-8"));
            this.ftpClient.changeWorkingDirectory(tempftpDirectory);// 改变工作路径
            success = this.ftpClient.storeFile(filename, is);
            if (success == true) {
                return success;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }


    /**
     * 
     * 类描述:    删除FTP上的文件夹
     * 参数:	  
     * 返回值:        void
     * @throws Exception
     */
    public void removeDirectoryFtp(String ftpHost, int ftpPort,
            String ftpUserName, String ftpPassword, String path) {

        FTPClient ftpClient = null;

        try {
            ftpClient = connectServer(ftpHost, ftpPort, ftpUserName,
                    ftpPassword);

            if (ftpClient.changeWorkingDirectory(path)) {

                FTPFile[] files = ftpClient.listFiles();

                if (files.length == 0) {
                    ftpClient.removeDirectory(path);
                } else {
                    for (int i = 0; i < files.length; i++) {

                        if (files[i].getType() == 0) {

                            ftpClient.deleteFile(files[i].getName());
                        } else {

                            if (files[i].getName().equals("..")
                                    || files[i].getName().equals(".")) {
                                continue;
                            }
                            removeDirectoryFtp(ftpHost, ftpPort, ftpUserName,
                                    ftpPassword,
                                    path + "/" + files[i].getName());
                        }
                    }
                    ftpClient.removeDirectory(path);
                }
            }

        } catch (final IOException ex) {
            ex.printStackTrace();
        } finally {
            if (ftpClient != null) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void makeDirectory(String dir) throws IOException {
        ftpClient.makeDirectory(dir);
    }


    /**
     * 退出FTP服务器
     * 
     * @throws Exception
     */
    public static void EpgFtpLogout() {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @return the ftpClient
     */
    public FTPClient getFtpClient() {
        return ftpClient;
    }

    /**
     * @param ftpClient the ftpClient to set
     */
    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }
    
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
public class FTPUtil { private FTPClient ftpClient=null; private boolean result = false; private FileInputStream fis; String ftpHost = "10.16.111.111"; String port = 21 String ftpUserName = "ftpuser11; String ftpPassword = "1234561"; /** * 登录服务器 * @param ftpInfo * @return * @throws IOException */ public FTPClient login() throws IOException { ftpClient = new FTPClient(); ftpClient.connect(ftpHost); boolean login = ftpClient.login(ftpUserName,ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); } if(login){ System.out.println("ftp成功!"); }else{ System.out.println("ftp失败!"); } //ftpClient.setControlEncoding("GBK"); return ftpClient; } /** * 字符串作为文件指定目录 下 * @param content 源字符串 * @param uploadDir 上目录 * @param ftpFileName 上文件名称 * @throws Exception */ public void ftpUploadByText(String content ,String uploadDir,String ftpFileName) throws Exception{ try { ftpClient = this.login(); //创建目录 createDir(ftpClient,uploadDir); // 设置上目录 这个也应该用配置文件读取 ftpClient.changeWorkingDirectory(uploadDir); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); String fileName = new String(ftpFileName.getBytes("GBK"),"iso-8859-1"); OutputStream os = ftpClient.storeFileStream(fileName); byte[] bytes = content.getBytes(); os.write(bytes); os.flush(); os.close(); } catch (Exception e) { ftpClient.disconnect(); ftpClient = null; e.printStackTrace(); throw e; }finally{ ftpClient.disconnect(); ftpClient = null; } } /** * 移动文件 * @param ftpInfo * @return * @throws Exception */ public boolean moveFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.moveFile(ftpClient, ftpInfo.getChangeWorkingDirectoryPath(), ftpInfo.getFilePath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 删除文件 * @param ftpInfo * @return * @throws Exception */ public boolean deleteFile(FTPInfo ftpInfo)throws Exception { boolean flag = false; try { ftpClient = this.login(); flag = this.deleteByFolder(ftpClient, ftpInfo.getChangeWorkingDirectoryPath()); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("关闭FTP发生异常!", e); }catch (Exception e) { e.printStackTrace(); throw e; } } return flag; } /** * 实现文件的移动,这里做的是一个文件夹下的所有内容移动到新的文件, * 如果要做指定文件移动,加个判断判断文件名 * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName) * @param ftp * @param oldPath * @param newPath * @return */ public boolean moveFile(FTPClient ftp,String oldPath,String newPath){ boolean flag = false; try { ftp.changeWorkingDirectory(oldPath); ftp.enterLocalPassiveMode(); //获取文件数组 FTPFile[] files = ftp.listFiles(); //新文件夹不存在则创建 if(!ftp.changeWorkingDirectory(newPath)){ ftp.makeDirectory(newPath); } //回到原有工作目录 ftp.changeWorkingDirectory(oldPath); for (FTPFile file : files) { if(file.isDirectory()) { moveFile(ftp,oldPath+file.getName()+"/" ,newPath+file.getName()+"/"); }else{ //转存目录 flag = ftp.rename(oldPath+new String(file.getName().getBytes("GBK"),"ISO-8859-1"), newPath+"/"+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } if(flag){ System.out.println(file.getName()+"移动成功"); }else{ System.out.println(file.getName()+"移动失败"); } } ftp.removeDirectory(new String(oldPath.getBytes("GBK"),"ISO-8859-1")); } catch (Exception e) { e.printStackTrace(); System.out.println("移动文件失败"); } return flag; } /** * 删除FTP上指定文件夹下文件及其子文件方法,添加了对中文目录的支持 * @param ftp FTPClient对象 * @param FtpFolder 需要删除文件夹 * @return */ public boolean deleteByFolder(FTPClient ftp,String FtpFolder){ boolean flag = false; try { ftp.changeWorkingDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); ftp.enterLocalPassiveMode(); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { //判断为文件删除 if(file.isFile()){ ftp.deleteFile(FtpFolder+new String(file.getName().getBytes("GBK"),"ISO-8859-1")); } //判断是文件夹 if(file.isDirectory()){ String childPath = FtpFolder +file.getName()+ "/"; //递归删除文件夹 deleteByFolder(ftp,childPath); } } //循环完成后删除文件夹 flag = ftp.removeDirectory(new String(FtpFolder.getBytes("GBK"),"ISO-8859-1")); if(flag){ System.out.println(FtpFolder+"文件删除成功"); }else{ System.out.println(FtpFolder+"文件删除成功"); } } catch (Exception e) { e.printStackTrace(); System.out.println("删除失败"); } return flag; } /** * 创建目录 * @param createpath * @param sftp */ public void createDir(FTPClient ftpClient,String createpath) throws Exception { try { if(ftpClient.changeWorkingDirectory(createpath)) { return; } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) { if (path.equals("")) { continue; } filePath.append(path + "/"); if(!ftpClient.changeWorkingDirectory(filePath.toString())) { ftpClient.makeDirectory(filePath.toString()); ftpClient.changeWorkingDirectory(filePath.toString()); } } ftpClient.changeWorkingDirectory(createpath); }catch (Exception e) { e.printStackTrace(); throw new Exception("创建路径错误:" + createpath); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值