//第一种方式,博客侧边栏公告

FtpUtils工具类 -实现获取zip下的json文件,上传、下载等功能

package cn.com.sparknet.merger.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

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.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FtpUtils {

    /**
     * 日志对象
     **/
     private static final Logger LOGGER = LoggerFactory.getLogger("cn.com.sparknet.merger.utils.FtpUtils");

    /**
     * FTP基础目录
     **/
    private static final String BASE_PATH = "/data-merger/";

    /**
     * 本地字符编码
     **/
    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);
                if (flag) {
                    LOGGER.info("上传成功");
                } else {
                    LOGGER.error("上传失败");
                }
            } catch (Exception e) {
                LOGGER.error("本地文件上传FTP失败", e);
            } finally {
                IOUtils.closeQuietly(fis);
                closeConnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 下载指定文件到本地
     *
     * @param ftpPath
     *            FTP服务器文件相对路径,例如:test/123
     * @param fileName
     *            要下载的文件名,例如:test.txt
     * @param savePath
     *            保存文件到本地的路径,例如:D:/test
     * @return 成功返回true,否则返回false
     */
    public static 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 static 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 static 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 = "192.168.1.144";
        int port = 21;
        String username = "nj_merger";
        String password = "Abcd1234";
        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;
    }

    /**
     * 判断文件是否存在
     *
     * @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;
    }

    /**
     * 去服务器的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, "utf-8"));
            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);
        }
    }
    
    /**
     * 实现文件的移动,这里做的是一个文件夹下的所有内容移动到新的文件,
     * 如果要做指定文件移动,加个判断判断文件名
     * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName)
     * @param ftp
     * @param oldPath
     * @param newPath
     * @return
     */
    public static boolean moveFile(String oldPath,String newPath,String fileName){
        boolean flag = false;
        // 登录
         FTPClient ftp = login();
        try {
            if (FTPReply.isPositiveCompletion(ftp.sendCommand(OPTS_UTF8, "ON"))) {
                localCharset = CHARSET_UTF8;
            }
            ftp.setControlEncoding(localCharset);
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            
            oldPath = changeEncoding(BASE_PATH + oldPath, ftp);
            newPath = changeEncoding(BASE_PATH + newPath, ftp);
            ftp.changeWorkingDirectory(oldPath);
            ftp.enterLocalPassiveMode();
            //获取文件数组
            FTPFile[] files = ftp.listFiles();
            //新文件夹不存在则创建
            if(!ftp.changeWorkingDirectory(newPath)){
                ftp.makeDirectory(newPath);
            }
            //回到原有工作目录
            ftp.changeWorkingDirectory(oldPath);
            for (FTPFile file : files) {
                String ftpName = file.getName();
                if (ftpName.equals(fileName)) {
                    //转存目录
                    flag = ftp.rename(new String(file.getName().getBytes(localCharset),serverCharset), newPath+File.separator+new String(file.getName().getBytes(localCharset),serverCharset));
                    //flag = ftp.rename(file.getName(), newPath+File.separator+file.getName());
                    break;
                }
            }
            if(flag){
                LOGGER.info(fileName+"移动成功");
            }else{
                LOGGER.error(fileName+"移动失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("移动文件失败");
        }
        return flag;
    }
    
    /**
     * 读取本地zip下的json文件
     * @param localPath
     * @param fileName
     * @return
     */
    public static String readJsonFile(String localPath, String fileName) {
        String jsonStr = "";
        // 登录
        try {
            File localFile = new File(localPath+File.separator+fileName);
            //得到输入流
            InputStream inputStream = new FileInputStream(localFile);
            ZipInputStream zin = new ZipInputStream(inputStream);
            ZipFile zf = new ZipFile(localFile);
            ZipEntry ze;
            while ((ze = zin.getNextEntry()) != null) {
                if (ze.toString().endsWith(".json")) {
                    //读取每个文件的字节,并放进数组
                    Reader reader = new InputStreamReader(zf.getInputStream(ze),"utf-8");
                    int ch = 0;
                    StringBuffer sb = new StringBuffer();
                    while ((ch = reader.read()) != -1) {
                        sb.append((char) ch);
                    }
                    reader.close();
                    jsonStr = sb.toString();
                }
            }
            zin.closeEntry();
            inputStream.close();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 读取ftp上zip下的json文件
     * @param ftpPath
     * @param fileName
     * @return
     */
    public static String readFileData(String ftpPath, String fileName) {
        FTPClient ftpClient = login();
        String jsonStr = "";
        try {
            // 设置编码:开启服务器对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)) {
                LOGGER.error(BASE_PATH + ftpPath + "该目录不存在");
                return jsonStr;
            }
            ftpClient.enterLocalPassiveMode();
            //得到输入流
            InputStream inputStream = getInputStreamByName(ftpPath, fileName);
            ZipInputStream zin = new ZipInputStream(inputStream);
            BufferedInputStream bs = new BufferedInputStream(zin);
            byte[] bytes = null;
            ZipEntry ze;
            //循环读取压缩包里面的文件
            while ((ze = zin.getNextEntry()) != null) {
                StringBuilder orginJson = new StringBuilder();
                if (ze.toString().endsWith(".json")) {
                    //读取每个文件的字节,并放进数组
                    bytes = new byte[(int) ze.getSize()];
                    bs.read(bytes, 0, (int) ze.getSize());
                    //将文件转成流
                    InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                    BufferedReader br = new BufferedReader(new InputStreamReader(byteArrayInputStream));
                    //读取文件里面的内容
                    String line;
                    while ((line = br.readLine()) != null) {
                        orginJson.append(line);
                    }
                    //关闭流
                    br.close();
                    jsonStr=orginJson.toString();
                }
            }
            zin.closeEntry();
            inputStream.close();
        } catch (FileNotFoundException e) {
            LOGGER.error("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            LOGGER.error("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("文件读取错误。");
            e.printStackTrace();
        }
        return jsonStr;
    }
    
    /**
     * 获取指定目录下的所有文件
     * @param ftpPath
     * @return
     * @throws Exception
     */
    public static List<String> getFileNameList(String ftpPath) throws Exception{
        FTPClient ftpClient = login();
        List<String> list = new ArrayList<String>();
        try {
            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)) {
                LOGGER.error(BASE_PATH + ftpPath + "该目录不存在");
                return list;
            }
             //获取文件数组
            FTPFile[] files = ftpClient.listFiles();
            for (FTPFile file : files) {
                String ftpName = file.getName();
                if(ftpName.endsWith(".zip")){
                    list.add(ftpName);
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        return list ;
    }
    public static int getJsonFileCount(String ftpPath, String fileName) {
        FTPClient ftpClient = login();
        int jsonCount = 0;
        try {
            // 设置编码:开启服务器对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)) {
                LOGGER.error(BASE_PATH + ftpPath + "该目录不存在");
                return -1;
            }
            ftpClient.enterLocalPassiveMode();
            //得到输入流
            InputStream inputStream = getInputStreamByName(ftpPath, fileName);
            ZipInputStream zin = new ZipInputStream(inputStream);
            ZipEntry ze;
            //循环读取压缩包里面的文件
            while ((ze = zin.getNextEntry()) != null) {
                if (ze.toString().endsWith(".json")) {
                    jsonCount++;
                }
            }
            zin.closeEntry();
            inputStream.close();
        } catch (FileNotFoundException e) {
            LOGGER.error("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            LOGGER.error("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("文件读取错误。");
            e.printStackTrace();
        }
        return jsonCount;
    }
    public static void main(String[] args) throws Exception {
        FtpUtils ftp = new FtpUtils();
//        //getFileInputStream("appkey01/upload/");
//        boolean uploadLocalFile = ftp.uploadLocalFile("appkey01/upload/","D:\\20210625.zip","20210625.zip");
//        System.out.println(uploadLocalFile);
//        String s = FtpUtils.readJsonFile("appkey01/upload/",  "20210625.zip");
//        String s = FtpUtils.readFileData("appkey01/upload/",  "20210625.zip");
//        System.out.println(s);
//        JSONObject jobj = JSON.parseObject(s);
//        JSONArray movies = jobj.getJSONArray("fileList");//构建JSONArray数组
//        FtpUtils.getInputStreamByName("appkey01/upload/",  "20210625.zip");
//        String readFile = FtpUtils.readFile("appkey01/upload/",  "20210625.zip");
//        System.out.println(readFile);
        boolean moveFile = moveFile("appkey01/upload", "appkey01/exception","20210625正确.zip");
        System.out.println(moveFile);
        List<String> fileNameList = getFileNameList("appkey01/exception");
        for (String string : fileNameList) {
            System.out.println(string);
        }
        
//        int jsonFileCount = getJsonFileCount("appkey02/upload","20210625.zip");
//        System.out.println(jsonFileCount);
        
    }

}

涉及jar的pom.xml

      <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->        
    <dependency>

       <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->  <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId>
       <version>3.2</version>
      </dependency> 
      <!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
      <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>2.2</version>
      </dependency>
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.9</version>
      </dependency>

 

posted @ 2021-07-06 15:32  zhoupan  阅读(360)  评论(0编辑  收藏  举报