ftp上傳

package com.br.sftpclient;import com.br.sftpUtil.PropertiesUtil;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPFile;import org.apache.commons.net.ftp.FTPReply;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;import org.springframework.util.StringUtils;import sun.rmi.runtime.Log;import java.io.*;import java.net.MalformedURLException;import java.util.logging.Logger;/** * @Company: * @Author: shaobin.fu * @Date: 2018/12/11 14:27 * @Description: */public class UpToFtp2 {    private transient org.slf4j.Logger log = LoggerFactory.getLogger(this.getClass());    private FTPClient ftp;    /**     * @param path     上傳到ftp服務器哪一個路徑下     * @param addr     地址     * @param port     端口號     * @param username 用戶名     * @param password 密碼     * @return     * @throws Exception     */    public boolean connect(String path, String addr, int port, String username, String password) throws Exception {        boolean result = false;        log.info("start connect.....");        ftp = new FTPClient();        int reply;        ftp.connect(addr, port);        ftp.login(username, password);        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);        reply = ftp.getReplyCode();        if (!FTPReply.isPositiveCompletion(reply)) {            ftp.disconnect();            return result;        }        log.info("ftp has been connected.....");        CreateDirecroty(path);        ftp.changeWorkingDirectory(path);        result = true;        return result;    }    //改變目錄路徑    public boolean changeWorkingDirectory(String directory) {        boolean flag = true;        try {            flag = ftp.changeWorkingDirectory(directory);            if (flag) {                log.info("enter " + directory + " success!");            } else {                log.info("enter " + directory + " failed!start create directory!");            }        } catch (IOException ioe) {            ioe.printStackTrace();        }        return flag;    }    //判斷ftp服務器文件是否存在    public boolean existFile(String path) throws IOException {        boolean flag = false;        FTPFile[] ftpFileArr = ftp.listFiles(path);        if (ftpFileArr.length > 0) {            flag = true;        }        return flag;    }    //建立目錄    public boolean makeDirectory(String dir) {        boolean flag = true;        try {            flag = ftp.makeDirectory(dir);            if (flag) {                log.info("create directory " + dir + " success!");            } else {                log.info("create directory " + dir + " failed!");            }        } catch (Exception e) {            e.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 {                        log.info("create directory " + subDirectory + " failed!");                        changeWorkingDirectory(subDirectory);                    }                } else {                    changeWorkingDirectory(subDirectory);                }                paths = paths + "/" + subDirectory;                start = end + 1;                end = directory.indexOf("/", start);                // 檢查全部目錄是否建立完畢                if (end <= start) {                    break;                }            }        }        return success;    }    /**     * @param file 上傳的文件或文件夾     * @throws Exception     */    public void upload(File file) throws Exception {        log.info("start upload,please waiting....");        if (file.isDirectory()) {            log.info("start upload,start upload directory....");           //ftp.makeDirectory(file.getName());            CreateDirecroty(file.getName());            ftp.changeWorkingDirectory(file.getName());            log.info("current pathname is:{}",file.getPath());            String[] files = file.list();            for (int i = 0; i < files.length; i++) {                log.info("file path:{}",file.getPath());                File file1 = new File(file.getPath() + "\\" + files[i]);                if (file1.isDirectory()) {                    upload(file1);                    ftp.changeToParentDirectory();                } else {                    File file2 = new File(file.getPath() + "\\" + files[i]);                    FileInputStream input = new FileInputStream(file2);                    ftp.storeFile(file2.getName(), input);                    input.close();                }            }        } else {            log.info("start upload,start upload file,wait a minute....");            File file2 = new File(file.getPath());            FileInputStream input = new FileInputStream(file2);            ftp.storeFile(file2.getName(), input);            input.close();        }    }    public static void main(String[] args) throws Exception {        UpToFtp2 t = new UpToFtp2();        t.connect("/huadong_fengkong/dir-name/", PropertiesUtil.getStringValue("hostname"), PropertiesUtil.getIntegerValue("port"),                PropertiesUtil.getStringValue("username"), PropertiesUtil.getStringValue("password"));        //String pathname = !StringUtils.isEmpty(args[0])?args[0]:PropertiesUtil.getStringValue("txt_path");        String pathname="E:\\opt\\SpringCloud";        File file = new File(pathname);        t.upload(file);    }}
相關文章
相關標籤/搜索