자바 작업 FTP 서버 유 니 버 설 도구 클래스

package cn.com.test.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * FTP     
 * 
 * @author:  Rodge
 * @time:    2017 12 24    23:02:37
 * @version: V1.0.0
 */
@Component
public class FTPUtil {

    /**      **/
    private static final Logger LOGGER = LoggerFactory.getLogger(FTPUtil.class);

    /** FTP   **/
    private static final String FTP_ADDRESS = "127.0.0.1";

    /** FTP   **/
    private static final int FTP_PORT = 21;

    /** FTP    **/
    private static final String FTP_USERNAME = "root";

    /** FTP   **/
    private static final String FTP_PASSWORD = "root";

    /** FTP     **/
    private static final String BASE_PATH = "ftp/";

    /**         **/
    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;
    
    /** FTPClient   **/
    private static FTPClient ftpClient = null;

    /**
     *        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) {
        //   
        login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        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);
                //      ,     
                if (!ftpClient.changeWorkingDirectory(path)) {
                    this.createDirectorys(path);
                }
                //       ,           
                ftpClient.enterLocalPassiveMode();
                //                
                flag = ftpClient.storeFile(new String(fileName.getBytes(localCharset), serverCharset), fis);
            } catch (Exception e) {
                LOGGER.error("      FTP  ", e);
            } finally {
                IOUtils.closeQuietly(fis);
                closeConnect();
            }
        }
        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) {
        //   
    	login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        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);
                //      ,     
                if (!ftpClient.changeWorkingDirectory(path)) {
                    this.createDirectorys(path);
                }
                //       ,           
                ftpClient.enterLocalPassiveMode();  
                //                
                flag = ftpClient.storeFile(new String(fileName.getBytes(localCharset), serverCharset), input);
            } catch (Exception e) {
                LOGGER.error("      FTP  ", e);
            } finally {
                closeConnect();
                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) {
        //   
    	login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        boolean flag = false;
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath);
                //          
                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();
            }
        }
        return flag;
    }

    /**
     *              
     * 
     * @param ftpPath FTP         ,  :test/123
     * @param savePath           ,  :D:/test
     * @return     true,    false
     */
    public boolean downloadFiles(String ftpPath, String savePath) {
        //   
    	login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        boolean flag = false;
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath);
                //          
                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();
            }
        }
        return flag;
    }

    /**
     *           ,       
     * 
     * @param ftpPath FTP            ,  :test/123
     * @return Map   key    ,value       
     */
    public Map getFileBytes(String ftpPath) {
        //   
    	login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        Map map = new HashMap<>();
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath);
                //          
                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();
            }
        }
        return map;
    }

    /**
     *         ,       
     * 
     * @param ftpPath FTP         ,  :test/123
     * @param fileName    ,  :test.xls
     * @return byte[]       
     */
    public byte[] getFileBytesByName(String ftpPath, String fileName) {
        //   
    	login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath);
                //          
                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();
            }
        }
        return byteStream.toByteArray();
    }

    /**
     *           ,      
     * 
     * @param ftpPath FTP          ,  :test/123
     * @return Map   key    ,value      
     */
    public Map getFileInputStream(String ftpPath) {
        //   
    	login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        Map map = new HashMap<>();
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath);
                //          
                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();
            }
        }
        return map;
    }

    /**
     *         ,      
     * 
     * @param ftpPath FTP          ,  :test/123
     * @param fileName    ,  :test.txt
     * @return InputStream      
     */
    public InputStream getInputStreamByName(String ftpPath, String fileName) {
        //   
    	login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        InputStream input = null;
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + ftpPath);
                //          
                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();
            }
        }
        return input;
    }

    /**
     *       
     * 
     * @param filePath       ,  :test/123/test.txt
     * @return     true,    false
     */
    public boolean deleteFile(String filePath) {
        //   
    	login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        boolean flag = false;
        if (ftpClient != null) {
            try {
                String path = changeEncoding(BASE_PATH + filePath);
                flag = ftpClient.deleteFile(path);
            } catch (IOException e) {
                LOGGER.error("      ", e);
            } finally {
                closeConnect();
            }
        }
        return flag;
    }

    /**
     *          
     *  
     * @param dirPath       ,  :test/123
     * @return     true,    false
     */
    public boolean deleteFiles(String dirPath) {
        //   
    	login(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD);
        boolean flag = false;
        if (ftpClient != null) {
            try {
                ftpClient.enterLocalPassiveMode();  //       ,           
                String path = changeEncoding(BASE_PATH + dirPath);
                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();
            }
        }
        return flag;
    }

    /**
     *   FTP   
     * 
     * @param address    , :127.0.0.1
     * @param port       , :21
     * @param username    , :root
     * @param password   , :root
     */
    private void login(String address, int port, String username, String password) {
        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();
                LOGGER.error("FTP       ");
            }
        } catch (Exception e) {
            LOGGER.error("FTP    ", e);
        }
    }

    /**
     *   FTP  
     * 
     */
    private void closeConnect() {
        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) {
        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;
    }
    
   /**
     *            
     * 
     * @param dirPath       
     * @return
     */
    private void createDirectorys(String dirPath) {  
        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);
        }
    }  
  
}

좋은 웹페이지 즐겨찾기