FtpUtil

package com.common.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author zbf
 * @create 2019/3/1 9:37
 **/
public class FtpUtil {

    /**
     * 日誌對象
     **/
    private static final Logger LOGGER = LoggerFactory.getLogger(FtpUtil.class);

    private static Properties ftpProperties = PropertiesUtil.quartzProperties("ftp.properties");
    /**
     * FTP基礎目錄
     **/
    private static final String BASE_PATH = ftpProperties.getProperty("ftp.path");

    /**
     * 本地字符編碼
     **/
    private static String localCharset = "GBK";

    /**
     * FTP協議裏面,規定文件名編碼爲iso-8859-1
     **/
    private static String serverCharset = "ISO-8859-1";

    /**
     * UTF-8字符編碼
     **/
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * OPTS UTF8字符串常量
     **/
    private static final String OPTS_UTF8 = "OPTS UTF8";

    /**
     * 設置緩衝區大小4M
     **/
    private static final int BUFFER_SIZE = 1024 * 1024 * 4;

    /**
     * 本地文件上傳到FTP服務器
     *
     * @param ftpPath  FTP服務器文件相對路徑,例如:test/123
     * @param savePath 本地文件路徑,例如:D:/test/123/test.txt
     * @param fileName 上傳到FTP服務的文件名,例如:666.txt
     * @return boolean 成功返回true,否則返回false
     */
    public boolean uploadLocalFile(String ftpPath, String savePath, String fileName) {
        // 登錄
        FTPClient ftpClient=login();
        boolean flag = false;
        if (ftpClient != null) {
            File file = new File(savePath);
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                ftpClient.setBufferSize(BUFFER_SIZE);
                // 設置編碼:開啓服務器對UTF-8的支持,如果服務器支持就用UTF-8編碼,否則就使用本地編碼(GBK)
                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                    localCharset = CHARSET_UTF8;
                }
                ftpClient.setControlEncoding(localCharset);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                String path = changeEncoding(BASE_PATH + ftpPath,ftpClient);
                // 目錄不存在,則遞歸創建
                if (!ftpClient.changeWorkingDirectory(path)) {
                    this.createDirectorys(path,ftpClient);
                }
                // 設置被動模式,開通一個端口來傳輸數據
                ftpClient.enterLocalPassiveMode();
                // 上傳文件
                flag = ftpClient.storeFile(new String(fileName.getBytes(localCharset), serverCharset), fis);
            } catch (Exception e) {
                LOGGER.error("本地文件上傳FTP失敗", e);
            } finally {
                IOUtils.closeQuietly(fis);
                closeConnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 遠程文件上傳到FTP服務器
     *
     * @param ftpPath    FTP服務器文件相對路徑,例如:test/123
     * @param remotePath 遠程文件路徑,例如:http://www.baidu.com/xxx/xxx.jpg
     * @param fileName   上傳到FTP服務的文件名,例如:test.jpg
     * @return boolean 成功返回true,否則返回false
     */
    public boolean uploadRemoteFile(String ftpPath, String remotePath, String fileName) {
        // 登錄
        FTPClient ftpClient=login();
        boolean flag = false;
        if (ftpClient != null) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            try {
                // 遠程獲取文件輸入流
                HttpGet httpget = new HttpGet(remotePath);
                response = httpClient.execute(httpget);
                HttpEntity entity = response.getEntity();
                InputStream input = entity.getContent();
                ftpClient.setBufferSize(BUFFER_SIZE);
                // 設置編碼:開啓服務器對UTF-8的支持,如果服務器支持就用UTF-8編碼,否則就使用本地編碼(GBK)
                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                    localCharset = CHARSET_UTF8;
                }
                ftpClient.setControlEncoding(localCharset);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                String path = changeEncoding(BASE_PATH + ftpPath,ftpClient);
                // 目錄不存在,則遞歸創建
                if (!ftpClient.changeWorkingDirectory(path)) {
                    this.createDirectorys(path,ftpClient);
                }
                // 設置被動模式,開通一個端口來傳輸數據
                ftpClient.enterLocalPassiveMode();
                // 上傳文件
                flag = ftpClient.storeFile(new String(fileName.getBytes(localCharset), serverCharset), input);
            } catch (Exception e) {
                LOGGER.error("遠程文件上傳FTP失敗", e);
            } finally {
                closeConnect(ftpClient);
                try {
                    httpClient.close();
                } catch (IOException e) {
                    LOGGER.error("關閉流失敗", e);
                }
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        LOGGER.error("關閉流失敗", e);
                    }
                }
            }
        }
        return flag;
    }

    /**
     * 下載指定文件到本地
     *
     * @param ftpPath  FTP服務器文件相對路徑,例如:test/123
     * @param fileName 要下載的文件名,例如:test.txt
     * @param savePath 保存文件到本地的路徑,例如:D:/test
     * @return 成功返回true,否則返回false
     */
    public boolean downloadFile(String ftpPath, String fileName, String savePath) {
        // 登錄
        FTPClient ftpClient=login();
        boolean flag = false;
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath,ftpClient);
                // 判斷是否存在該目錄
                if (!ftpClient.changeWorkingDirectory(path)) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄不存在");
                    return flag;
                }
                ftpClient.enterLocalPassiveMode();  // 設置被動模式,開通一個端口來傳輸數據
                String[] fs = ftpClient.listNames();
                // 判斷該目錄下是否有文件
                if (fs == null || fs.length == 0) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄下沒有文件");
                    return flag;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    if (ftpName.equals(fileName)) {
                        File file = new File(savePath + '/' + ftpName);
                        try (OutputStream os = new FileOutputStream(file)) {
                            flag = ftpClient.retrieveFile(ff, os);
                        } catch (Exception e) {
                            LOGGER.error(e.getMessage(), e);
                        }
                        break;
                    }
                }
            } catch (IOException e) {
                LOGGER.error("下載文件失敗", e);
            } finally {
                closeConnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 下載該目錄下所有文件到本地
     *
     * @param ftpPath  FTP服務器上的相對路徑,例如:test/123
     * @param savePath 保存文件到本地的路徑,例如:D:/test
     * @return 成功返回true,否則返回false
     */
    public boolean downloadFiles(String ftpPath, String savePath) {
        // 登錄
        FTPClient ftpClient=login();
        boolean flag = false;
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath,ftpClient);
                // 判斷是否存在該目錄
                if (!ftpClient.changeWorkingDirectory(path)) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄不存在");
                    return flag;
                }
                ftpClient.enterLocalPassiveMode();  // 設置被動模式,開通一個端口來傳輸數據
                String[] fs = ftpClient.listNames();
                // 判斷該目錄下是否有文件
                if (fs == null || fs.length == 0) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄下沒有文件");
                    return flag;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    File file = new File(savePath + '/' + ftpName);
                    try (OutputStream os = new FileOutputStream(file)) {
                        ftpClient.retrieveFile(ff, os);
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
                flag = true;
            } catch (IOException e) {
                LOGGER.error("下載文件失敗", e);
            } finally {
                closeConnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 獲取該目錄下所有文件,以字節數組返回
     *
     * @param ftpPath FTP服務器上文件所在相對路徑,例如:test/123
     * @return Map<String                                                               ,                                                                                                                               Object> 其中key爲文件名,value爲字節數組對象
     */
    public Map<String, byte[]> getFileBytes(String ftpPath) {
        // 登錄
        FTPClient ftpClient=login();
        Map<String, byte[]> map = new HashMap<>();
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath,ftpClient);
                // 判斷是否存在該目錄
                if (!ftpClient.changeWorkingDirectory(path)) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄不存在");
                    return map;
                }
                ftpClient.enterLocalPassiveMode();  // 設置被動模式,開通一個端口來傳輸數據
                String[] fs = ftpClient.listNames();
                // 判斷該目錄下是否有文件
                if (fs == null || fs.length == 0) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄下沒有文件");
                    return map;
                }
                for (String ff : fs) {
                    try (InputStream is = ftpClient.retrieveFileStream(ff)) {
                        String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
                        byte[] buffer = new byte[BUFFER_SIZE];
                        int readLength = 0;
                        while ((readLength = is.read(buffer, 0, BUFFER_SIZE)) > 0) {
                            byteStream.write(buffer, 0, readLength);
                        }
                        map.put(ftpName, byteStream.toByteArray());
                        ftpClient.completePendingCommand(); // 處理多個文件
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
            } catch (IOException e) {
                LOGGER.error("獲取文件失敗", e);
            } finally {
                closeConnect(ftpClient);
            }
        }
        return map;
    }

    /**
     * 根據名稱獲取文件,以字節數組返回
     *
     * @param ftpPath  FTP服務器文件相對路徑,例如:test/123
     * @param fileName 文件名,例如:test.xls
     * @return byte[] 字節數組對象
     */
    public byte[] getFileBytesByName(String ftpPath, String fileName) {
        // 登錄
        FTPClient ftpClient=login();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath,ftpClient);
                // 判斷是否存在該目錄
                if (!ftpClient.changeWorkingDirectory(path)) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄不存在");
                    return byteStream.toByteArray();
                }
                ftpClient.enterLocalPassiveMode();  // 設置被動模式,開通一個端口來傳輸數據
                String[] fs = ftpClient.listNames();
                // 判斷該目錄下是否有文件
                if (fs == null || fs.length == 0) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄下沒有文件");
                    return byteStream.toByteArray();
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    if (ftpName.equals(fileName)) {
                        try (InputStream is = ftpClient.retrieveFileStream(ff);) {
                            byte[] buffer = new byte[BUFFER_SIZE];
                            int len = -1;
                            while ((len = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
                                byteStream.write(buffer, 0, len);
                            }
                        } catch (Exception e) {
                            LOGGER.error(e.getMessage(), e);
                        }
                        break;
                    }
                }
            } catch (IOException e) {
                LOGGER.error("獲取文件失敗", e);
            } finally {
                closeConnect(ftpClient);
            }
        }
        return byteStream.toByteArray();
    }

    /**
     * 獲取該目錄下所有文件,以輸入流返回
     *
     * @param ftpPath FTP服務器上文件相對路徑,例如:test/123
     * @return  Map<String, InputStream>                                                               ,                                                                                                                               InputStream> 其中key爲文件名,value爲輸入流對象
     */
    public Map<String, InputStream> getFileInputStream(String ftpPath) {
        // 登錄
        FTPClient ftpClient=login();
        Map<String, InputStream> map = new HashMap<>();
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath,ftpClient);
                // 判斷是否存在該目錄
                if (!ftpClient.changeWorkingDirectory(path)) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄不存在");
                    return map;
                }
                ftpClient.enterLocalPassiveMode();  // 設置被動模式,開通一個端口來傳輸數據
                String[] fs = ftpClient.listNames();
                // 判斷該目錄下是否有文件
                if (fs == null || fs.length == 0) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄下沒有文件");
                    return map;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    InputStream is = ftpClient.retrieveFileStream(ff);
                    map.put(ftpName, is);
                    ftpClient.completePendingCommand(); // 處理多個文件
                }
            } catch (IOException e) {
                LOGGER.error("獲取文件失敗", e);
            } finally {
                closeConnect(ftpClient);
            }
        }
        return map;
    }

    /**
     * 根據名稱獲取文件,以輸入流返回
     *
     * @param ftpPath  FTP服務器上文件相對路徑,例如:test/123
     * @param fileName 文件名,例如:test.txt
     * @return InputStream 輸入流對象
     */
    public static InputStream getInputStreamByName(String ftpPath, String fileName) {
        // 登錄
        FTPClient ftpClient=login();
        InputStream input = null;
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath,ftpClient);
                // 判斷是否存在該目錄
                if (!ftpClient.changeWorkingDirectory(path)) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄不存在");
                    return input;
                }
                ftpClient.enterLocalPassiveMode();  // 設置被動模式,開通一個端口來傳輸數據
                String[] fs = ftpClient.listNames();
                // 判斷該目錄下是否有文件
                if (fs == null || fs.length == 0) {
                    LOGGER.error(BASE_PATH + ftpPath + "該目錄下沒有文件");
                    return input;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    if (ftpName.equals(fileName)) {
                        input = ftpClient.retrieveFileStream(ff);
                        break;
                    }
                }
            } catch (IOException e) {
                LOGGER.error("獲取文件失敗", e);
            } finally {
                closeConnect(ftpClient);
            }
        }
        return input;
    }

    /**
     * 刪除指定文件
     *
     * @param filePath 文件相對路徑,例如:test/123/test.txt
     * @return 成功返回true,否則返回false
     */
    public boolean deleteFile(String filePath) {
        // 登錄
        FTPClient ftpClient=login();
        boolean flag = false;
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + filePath,ftpClient);
                flag = ftpClient.deleteFile(path);
            } catch (IOException e) {
                LOGGER.error("刪除文件失敗", e);
            } finally {
                closeConnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 刪除目錄下所有文件
     *
     * @param dirPath 文件相對路徑,例如:test/123
     * @return 成功返回true,否則返回false
     */
    public boolean deleteFiles(String dirPath) {
        // 登錄
        FTPClient ftpClient=login();
        boolean flag = false;
        if (ftpClient != null) {
            try {
                ftpClient.enterLocalPassiveMode();  // 設置被動模式,開通一個端口來傳輸數據
                String path = changeEncoding(BASE_PATH + dirPath,ftpClient);
                String[] fs = ftpClient.listNames(path);
                // 判斷該目錄下是否有文件
                if (fs == null || fs.length == 0) {
                    LOGGER.error(BASE_PATH + dirPath + "該目錄下沒有文件");
                    return flag;
                }
                for (String ftpFile : fs) {
                    ftpClient.deleteFile(ftpFile);
                }
                flag = true;
            } catch (IOException e) {
                LOGGER.error("刪除文件失敗", e);
            } finally {
                closeConnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 連接FTP服務器
     *
     */
    private static FTPClient login() {
        String address=ftpProperties.getProperty("ftp.server");
        int port=Integer.valueOf(ftpProperties.getProperty("ftp.port"));
        String username=ftpProperties.getProperty("ftp.loginName");
        String password=ftpProperties.getProperty("ftp.loginPassword");
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(address, port);
            ftpClient.login(username, password);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                closeConnect(ftpClient);
                LOGGER.error("FTP服務器連接失敗");
            }
        } catch (Exception e) {
            LOGGER.error("FTP登錄失敗", e);
        }
        return ftpClient;
    }

    /**
     * 關閉FTP連接
     */
    private static void closeConnect(FTPClient ftpClient) {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                LOGGER.error("關閉FTP連接失敗", e);
            }
        }
    }

    /**
     * FTP服務器路徑編碼轉換
     *
     * @param ftpPath FTP服務器路徑
     * @return String
     */
    private static String changeEncoding(String ftpPath,FTPClient ftpClient) {
        String directory = null;
        try {
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                localCharset = CHARSET_UTF8;
            }
            directory = new String(ftpPath.getBytes(localCharset), serverCharset);
        } catch (Exception e) {
            LOGGER.error("路徑編碼轉換失敗", e);
        }
        return directory;
    }

    /**
     * 本地文件上傳到FTP服務器
     *
     * @param ftpPath  FTP服務器文件相對路徑,例如:test/123
     * @param content 文件內容
     * @param fileName 上傳到FTP服務的文件名,例如:666.txt
     * @return boolean 成功返回true,否則返回false
     */
    public static boolean createFile(String ftpPath, String fileName, String content, FTPClient ftpClient) {
        boolean flag = false;
        if (ftpClient != null) {
            InputStream fis = null;
            try {
                ftpClient.setBufferSize(BUFFER_SIZE);
                // 設置編碼:開啓服務器對UTF-8的支持,如果服務器支持就用UTF-8編碼,否則就使用本地編碼(GBK)
                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                    localCharset = CHARSET_UTF8;
                }
                fis = new ByteArrayInputStream(content.getBytes(localCharset));
                ftpClient.setControlEncoding(localCharset);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                String path = changeEncoding(BASE_PATH + ftpPath,ftpClient);
                // 目錄不存在,則遞歸創建
                if (!ftpClient.changeWorkingDirectory(path)) {
                    createDirectorys(path,ftpClient);
                }
                // 設置被動模式,開通一個端口來傳輸數據
                ftpClient.enterLocalPassiveMode();
                // 上傳文件
                flag = ftpClient.storeFile(new String(fileName.getBytes(localCharset), serverCharset), fis);
            } catch (Exception e) {
                LOGGER.error("本地文件上傳FTP失敗", e);
            } finally {
                IOUtils.closeQuietly(fis);
                closeConnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 本地上傳文件到FTP服務器
     *
     * @param filePath 遠程文件路徑FTP
     */
    public static boolean appendFile(String filePath, String fileName, String content, FTPClient ftpClient) {
        boolean flag = false;
        if (ftpClient != null) {
            InputStream fis = null;
            try {
                ftpClient.setBufferSize(BUFFER_SIZE);
                // 設置編碼:開啓服務器對UTF-8的支持,如果服務器支持就用UTF-8編碼,否則就使用本地編碼(GBK)
                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                    localCharset = CHARSET_UTF8;
                }
                fis = new ByteArrayInputStream(("\n"+content).getBytes(localCharset));
                ftpClient.setControlEncoding(localCharset);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                String path = changeEncoding(BASE_PATH + filePath,ftpClient);
                ftpClient.changeWorkingDirectory(path);
                // 設置被動模式,開通一個端口來傳輸數據
                ftpClient.enterLocalPassiveMode();
                // 追加文件
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile file : ftpFiles) {
                    String ftpName = file.getName();
                    if (ftpName.equals(fileName)) {
                        ftpClient.setRestartOffset(file.getSize());
                        ftpName = new String(file.getName().getBytes(localCharset), serverCharset);
                        flag = ftpClient.appendFile(ftpName,fis);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("文件追加失敗", e);
            } finally {
                IOUtils.closeQuietly(fis);
                closeConnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 判斷文件是否存在
     *
     * @param filePath 遠程文件路徑FTP
     * @throws IOException
     */
    public static Boolean isFileExist(String filePath, String fileName, FTPClient ftpClient) {
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + filePath,ftpClient);
                // 判斷是否存在該目錄
                if (!ftpClient.changeWorkingDirectory(path)) {
                    LOGGER.error(BASE_PATH + filePath + "該目錄不存在");
                    return false;
                }
                ftpClient.enterLocalPassiveMode();  // 設置被動模式,開通一個端口來傳輸數據
                String[] fs = ftpClient.listNames();
                // 判斷該目錄下是否有文件
                if (fs == null || fs.length == 0) {
                    LOGGER.error(BASE_PATH + filePath + "該目錄下沒有文件");
                    return false;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    if (ftpName.equals(fileName)) {
                        return true;
                    }
                }
            } catch (IOException e) {
                LOGGER.error("獲取文件失敗", e);
            }
        }
        return false;
    }

    /**
     * 創建 日誌
     * @param filePath
     * @param fileName
     * @param content
     */
    public static void createLogFile(String filePath, String fileName, String content){
        FTPClient ftpClient = login();
        if(isFileExist(filePath,fileName,ftpClient)){
            appendFile(filePath,fileName,content,ftpClient);
        }else{
            createFile(filePath,fileName,content,ftpClient);
        }
    }
    /**
     * 去服務器的FTP路徑下上讀取文件
     *
     * @param ftpPath
     * @param fileName
     * @return
     */
    public static String readFile(String ftpPath,String fileName) throws Exception {
        StringBuffer result = new StringBuffer();
        InputStream in = getInputStreamByName(ftpPath,fileName);
        if (in != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(in,localCharset));
            String str = null;
            try {
                while ((str = br.readLine()) != null) {
                    result.append(StringUtils.isNotBlank(result.toString())?System.lineSeparator()+str:str);
                }
            } catch (IOException e) {
                LOGGER.error("文件讀取錯誤。");
                e.printStackTrace();
                return "文件讀取失敗,請聯繫管理員.";
            }
        }else{
            LOGGER.error("in爲空,不能讀取。");
            return "文件讀取失敗,請聯繫管理員.";
        }
        return result.toString();
    }

    /**
     *      * 在服務器上遞歸創建目錄
     *      *
     *      * @param dirPath 上傳目錄路徑
     *      * @return
     *     
     */
    private static void createDirectorys(String dirPath, FTPClient ftpClient) {
        try {
            if (!dirPath.endsWith("/")) {
                dirPath += "/";
            }
            String directory = dirPath.substring(0, dirPath.lastIndexOf("/") + 1);
            ftpClient.makeDirectory("/");
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            while (true) {
                String subDirectory = new String(dirPath.substring(start, end));
                if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                    if (ftpClient.makeDirectory(subDirectory)) {
                        ftpClient.changeWorkingDirectory(subDirectory);
                    } else {
                        LOGGER.info("創建目錄失敗");
                        return;
                    }
                }
                start = end + 1;
                end = directory.indexOf("/", start);
                //檢查所有目錄是否創建完畢
                if (end <= start) {
                    break;
                }
            }
        } catch (
                Exception e)

        {
            LOGGER.error("上傳目錄創建失敗", e);
        }
    }

    public static void main(String[] args) throws Exception {

        String path = ftpProperties.getProperty("ftp.path");

        appendFile("test/2019/03-01","test.log","中文字符串",login());
//        createFile("log/2019/03-01","測試文件.txt","文件內容",login());

//        System.out.println(isFileExist("/log/2019/03-01","test.log",login()));
        String fileContent = readFile("log/2019/03-01","test.log");
        System.out.println(fileContent);
    }

}
ftp.properties

ftp.loginName=*****
ftp.loginPassword=***
ftp.server=*.*.*.*
ftp.port=21
ftp.path=/resource/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章