Java FTP輔助類

一、添加FTP Maven依賴java

       <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>

 

二、建立FtpUtils類apache

package com.wap.common;


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.LogManager;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.MalformedURLException;

public class FtpUtils {
    private static final Logger LOG = LogManager.getLogger(FtpUtils.class);
    //服務器地址
    private static String hostname ="192.168.1.1";
    //服務器端口
    private static int port = "22";
    //服務器帳號
    private static String username = "root";
    //服務器密碼
    private static String password = "123456";

    public static String pathname="/files/upload";


    public FTPClient ftpClient = null;

    /**
     * 初始化ftp服務器
     */
    public void initFtpClient() {
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        try {
            LOG.info("connecting...ftp服務器:"+this.hostname+":"+this.port);
            System.out.println("connecting...ftp服務器:"+this.hostname+":"+this.port);
            ftpClient.connect(hostname, port); //鏈接ftp服務器
            ftpClient.login(username, password); //登陸ftp服務器
            int replyCode = ftpClient.getReplyCode(); //是否成功登陸服務器
            if(!FTPReply.isPositiveCompletion(replyCode)){
                System.out.println("connect failed...ftp服務器:"+this.hostname+":"+this.port);
                LOG.info("connect failed...ftp服務器:"+this.hostname+":"+this.port);
            }else {
                System.out.println("connect successfu...ftp服務器:"+this.hostname+":"+this.port);
                LOG.info("connect successfu...ftp服務器:"+this.hostname+":"+this.port);
            }

        }catch (MalformedURLException e) {
            e.printStackTrace();
            LOG.info("connect failed...error:"+e.getMessage());
        }catch (IOException e) {
            e.printStackTrace();
            LOG.info("connect failed...error:"+e.getMessage());
        }
    }

    /**
     * 上傳文件
     * @parampathname ftp服務保存地址
     * @param fileName 上傳到ftp的文件名
     *  @param originfilename 待上傳文件的名稱(絕對地址) *
     * @return
     */
    public boolean uploadFile(String fileName,String originfilename){
        boolean flag = false;
        InputStream inputStream = null;
        try{
            LOG.info("開始上傳文件");
            System.out.println("開始上傳文件");
            inputStream = new FileInputStream(new File(originfilename));
            initFtpClient();
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
            CreateDirecroty(pathname);
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            ftpClient.logout();
            flag = true;
            LOG.info("上傳文件成功");
            System.out.println("上傳文件成功");
        }catch (Exception e) {
            LOG.info("上傳文件失敗");
            System.out.println("上傳文件失敗");
            e.printStackTrace();
        }finally{
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
    /**
     * 上傳文件
     * @param pathname ftp服務保存地址
     * @param fileName 上傳到ftp的文件名
     * @param inputStream 輸入文件流
     * @return
     */
    public boolean uploadFile( String pathname, String fileName,InputStream inputStream){
        boolean flag = false;
        try{
            System.out.println("開始上傳文件");
            initFtpClient();
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
            CreateDirecroty(pathname);
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            ftpClient.logout();
            flag = true;
            System.out.println("上傳文件成功");
        }catch (Exception e) {
            System.out.println("上傳文件失敗");
            e.printStackTrace();
        }finally{
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }
    //改變目錄路徑
    public boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                System.out.println("進入文件夾" + directory + " 成功!");

            } else {
                System.out.println("進入文件夾" + directory + " 失敗!開始建立文件夾");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    //建立多層目錄文件,若是有ftp服務器已存在該文件,則不建立,若是無,則建立
    public boolean CreateDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote + "/";
        // 若是遠程目錄不存在,則遞歸建立遠程服務器目錄
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        System.out.println("建立目錄[" + subDirectory + "]失敗");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 檢查全部目錄是否建立完畢
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    //判斷ftp服務器文件是否存在
    public boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }
    //建立目錄
    public boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = ftpClient.makeDirectory(dir);
            if (flag) {
                System.out.println("建立文件夾" + dir + " 成功!");

            } else {
                System.out.println("建立文件夾" + dir + " 失敗!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /** * 下載文件 *
     * @param pathname FTP服務器文件目錄 *
     * @param filename 文件名稱 *
     * @param localpath 下載後的文件路徑 *
     * @return */
    public  boolean downloadFile(String pathname, String filename, String localpath){
        boolean flag = false;
        OutputStream os=null;
        try {
            System.out.println("開始下載文件");
            initFtpClient();
            //切換FTP目錄
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for(FTPFile file : ftpFiles){
                if(filename.equalsIgnoreCase(file.getName())){
                    File localFile = new File(localpath + "/" + file.getName());
                    os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), os);
                    os.close();
                }
            }
            ftpClient.logout();
            flag = true;
            System.out.println("下載文件成功");
        } catch (Exception e) {
            System.out.println("下載文件失敗");
            e.printStackTrace();
        } finally{
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /** * 刪除文件 *
     * @param pathname FTP服務器保存目錄 *
     * @param filename 要刪除的文件名稱 *
     * @return */
    public boolean deleteFile(String pathname, String filename){
        boolean flag = false;
        try {
            System.out.println("開始刪除文件");
            initFtpClient();
            //切換FTP目錄
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
            System.out.println("刪除文件成功");
        } catch (Exception e) {
            System.out.println("刪除文件失敗");
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        FtpUtils ftp =new FtpUtils();
        //ftp.uploadFile("ftpFile/data", "123.docx", "E://123.docx");
        //ftp.downloadFile("ftpFile/data", "123.docx", "F://");
        ftp.deleteFile("ftpFile/data", "123.docx");
        System.out.println("ok");
    }
}
相關文章
相關標籤/搜索