java代码的几个utils,基本可以直接用

public class MD5Util {

    // 字符串的MD5
    public static String string2MD5(String psw) {
        {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(psw.getBytes("UTF-8"));
                byte[] encryption = md5.digest();
                StringBuffer strBuf = new StringBuffer();
                for (int i = 0; i < encryption.length; i++) {
                    if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                        strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                    } else {
                        strBuf.append(Integer.toHexString(0xff & encryption[i]));
                    }
                }
                return strBuf.toString();
            } catch (NoSuchAlgorithmException e) {
                return "";
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        }
    }

}
生成MD5
public class DateUtils {

    public static String local2utc(String localTime) {
        //String localTime = "2018-05-23 16:05:52";
        String utcTimePatten = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
        String localTimePatten = "yyyy-MM-dd HH:mm:ss";

        SimpleDateFormat localFormat = new SimpleDateFormat(localTimePatten);
        localFormat.setTimeZone(TimeZone.getDefault()); // 设置本地时区 自动计算出本地时间
        try {
            Date gpsUTCDate = localFormat.parse(localTime);
            SimpleDateFormat utcFormat = new SimpleDateFormat(utcTimePatten);
            utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));// 时区定义并进行时间获取
            String utcTime = utcFormat.format(gpsUTCDate.getTime());

            //System.out.println(localTime);
            //System.out.println(utcTime);

            return utcTime;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * UTC时间转本地时间格式
     * 
     * @param utcTime         UTC时间
     * @param utcTimePatten   UTC时间格式
     * @param localTimePatten 本地时间格式
     * @return 本地时间格式的时间
     */
    public static String utc2Local(String utcTime) {
        //String utcTime = "2018-05-23T16:05:52.123Z";
        String utcTimePatten = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
        String localTimePatten = "yyyy-MM-dd HH:mm:ss";
        System.out.println(utcTime);

        SimpleDateFormat utcFormat = new SimpleDateFormat(utcTimePatten);
        utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));// 时区定义并进行时间获取
        try {
            Date gpsUTCDate = utcFormat.parse(utcTime);

            SimpleDateFormat localFormat = new SimpleDateFormat(localTimePatten);
            localFormat.setTimeZone(TimeZone.getDefault()); // 设置本地时区 自动计算出本地时间
            String localTime = localFormat.format(gpsUTCDate.getTime());
            //System.out.println(localTime);
            return localTime;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String local2utc(Date date) {
        String localTimePatten = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat localFormat = new SimpleDateFormat(localTimePatten);
        String local = localFormat.format(new Date());
        return local2utc(local);
    }

}
utc日期转换
public class StringUtils {

    public static String truncStr(String str, int length) {
        if (hasLength(str)) {
            if (str.length() > length) {
                str = str.substring(0, length);
            }
        }
        return str;
    }

    public static boolean hasLength(String str) {
        return (str != null && str.length() > 0);
    }

    public static Long toLong(String strValue) {
        long lng = (strValue == null ? 0 : Long.parseLong(strValue));
        return (new Long(lng));
    }

    public static Integer toInteger(String strValue) {
        int lng = (strValue == null ? 0 : Integer.parseInt(strValue));
        return (new Integer(lng));
    }

    public static Byte toByte(String strValue) {
        byte bt = (strValue == null ? 0 : Byte.parseByte(strValue));
        return (new Byte(bt));
    }

    public static Boolean toBoolean(String strValue) {
        return new Boolean(toBool(strValue));
    }

    public static boolean toBool(String strValue) {
        if (strValue == null) {
            return false;
        } else if (strValue.length() > 0) {
            strValue = strValue.toUpperCase();
            char b = strValue.charAt(0);
            switch (b) {
            case 'T':
            case '1':
            case '是':
                return true;
            case 'F':
            case '0':
            case '否':
                return false;
            default:
                return false;
            }
        } else {
            return false;
        }
    }

    public static java.sql.Timestamp toSQLTimestamp(String value) {
        return (new java.sql.Timestamp(toDate(value).getTime()));
    }

    public static java.util.Date toDate(String strValue) {
        SimpleDateFormat fmt = null;

        if (strValue.indexOf('.') > 0) {
            fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);// 2005-01-01
            // 10:10:10.100
        } else if (strValue.indexOf(':') > 0) {
            fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 2005-01-01
            // 10:10:10.100
        } else if (strValue.indexOf('-') > 0) {
            fmt = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);// 2005-01-01
            // 10:10:10.100
        }

        try {
            return fmt.parse(strValue);
        } catch (ParseException ex) {
            return new Date(0);// 返回1970-01-01 00:00:00
        }
    }

    /**
     * 使用2005-01-01 10:10:10.456格式返回Date
     * 
     * @param date
     *            Date
     * @return String
     */
    public static String toString(java.util.Date date) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 2005-01-01
        // 10:10:10.100
        return fmt.format(date);
    }

    public static String toString(java.util.Date date, boolean bolWithMS) {
        SimpleDateFormat fmt;
        if (bolWithMS) {
            fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA); // 2005-01-01
            // 10:10:10.100
        } else {
            fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);// 2005-01-01
            // 10:10:10.100
        }
        return fmt.format(date);
    }

    /**
     * 采用1、0表示boolean
     * 
     * @param b
     *            boolean
     * @return String
     */
    public static String toString(boolean b) {
        return (b ? "1" : "0");
    }

    /**
     * 如果locale是CHINA用“是”、“否”表示boolean 如果locale是null用“1”、“0”表示boolean
     * 其他情况下用“true”、“false”表示boolean
     * 
     * @param b
     *            boolean
     * @param locale
     *            Locale
     * @return String
     */
    public static String toString(boolean b, Locale locale) {
        if (locale == Locale.CHINA) {
            return (b ? "是" : "否");
        } else if (locale == null) {
            return (b ? "1" : "0");
        } else {// 不管了

            return (b ? "true" : "false");
        }
    }

    /**
     * 把ip转换为长整型
     * 
     * @param ip
     *            String
     * @return long
     */
    public static long ParseIp2Long(String ip) {
        Long num = 0L;
        if (ip == null) {
            return num;
        }

        try {
            ip = ip.replaceAll("[^0-9\\.]", ""); // 去除字符串前的空字符
            String[] ips = ip.split("\\.");
            if (ips.length == 4) {
                num = Long.parseLong(ips[0], 10) * 256L * 256L * 256L + Long.parseLong(ips[1], 10) * 256L * 256L
                        + Long.parseLong(ips[2], 10) * 256L + Long.parseLong(ips[3], 10);
                num = num >>> 0;
            }
        } catch (NullPointerException ex) {
            return 0L;
        }

        return num;
    }
    
}
StringUtils
public final class AESUtils {
  //mode用aes的话,默认aes/ECB/NoPadding/128
  public static final String AES = "AES";
  private Cipher encryptCipher;
  private Cipher decryptCipher;
  private SecretKeySpec secretKey;
  private String mode;

  private AESUtils(SecretKeySpec secretKey, String mode) {
    this.secretKey = secretKey;
    this.mode = mode;
  }



  public static AESUtils aesECBNoPadding128(String seed) {
    return new AESUtils(new SecretKeySpec(seed.getBytes(), AES), AES);
  }


  public String encrypt(String v) throws Exception {
    if (encryptCipher == null) {
      encryptCipher = Cipher.getInstance(mode); // 算法是AES
      encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
    }
    return Base64Utils.encodeToString(encryptCipher.doFinal(v.getBytes(StandardCharsets.UTF_8)));
  }

  public String decrypt(String v) throws Exception {
    if (decryptCipher == null) {
      decryptCipher = Cipher.getInstance(mode); // 算法是AES
      decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
    }
    byte[] clearTextBytes = decryptCipher.doFinal(Base64Utils.decodeFromString(v));
    return new String(clearTextBytes, StandardCharsets.UTF_8);
  }
}
AESUtils
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class FFMpegUtils {

    private final static Logger logger = LoggerFactory
            .getLogger(FFMpegUtils.class);

    public static boolean isSurpportedType(String type) {
        Pattern pattern = Pattern.compile(
                "(asx|asf|mpg|wmv|3gp|mp4|mov|avi|flv|ts|jpg|png|bmp){1}$",
                Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(type);
        return matcher.find();
    }

    private static boolean resizeImage(String srcImagePath, String toImagePath,
            int width, int height) throws IOException {
        try {
            // 读入文件
            File file = new File(srcImagePath);
            // 构造Image对象
            BufferedImage src = ImageIO.read(file);
            // 放大边长
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            // 绘制放大后的图片
            tag.getGraphics().drawImage(src, 0, 0, width, height, null);

            ImageIO.write(tag, "jpg", new File(toImagePath));
            return new File(toImagePath).exists();
        } catch (Throwable e) {
            logger.warn("ImageIO不能处理文件{}" + srcImagePath, e);
            return false;
        }
    }

    public static boolean captureThumbnail(String ffmpegPath,
            String sourceFile, String destination, String aspectratio,
            String position, boolean isSynchronized) throws IOException,
            InterruptedException {
        String lowerCase = sourceFile.toLowerCase();
        if (lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg")
                || lowerCase.endsWith(".png") || lowerCase.endsWith(".bmp")
                || lowerCase.endsWith(".gif")) {
            String[] sizes = aspectratio.split("\\*");
            if (resizeImage(sourceFile, destination,
                    Integer.parseInt(sizes[0]), Integer.parseInt(sizes[1]))) {
                return true;
            }
        }

        boolean result = true;
        // http协议会返回 !exists
        // File video = new File(sourceFile);
        // if (!video.exists() || video.length() == 0) {
        // throw new IOException("file does not exists or leng is 0!");
        // }

        List<String> cmd = new LinkedList<String>();
        cmd.add(ffmpegPath);
        cmd.add("-y");
        if (StringUtils.hasLength(position)) {
            cmd.add("-ss");
            cmd.add(position);
        }
        cmd.add("-i");
        cmd.add(sourceFile);
        cmd.add("-s");
        cmd.add(aspectratio);
        cmd.add("-t");
        cmd.add("0.001");
        cmd.add("-f");
        cmd.add("image2");

        cmd.add(destination.replaceAll("%", "%%"));

        ProcessBuilder pb = new ProcessBuilder();
        pb.redirectErrorStream(true);
        pb.command(cmd);
        long start = System.currentTimeMillis();
        File file = new File(destination);
        file.getParentFile().mkdirs();
        pb.start();
        while (isSynchronized) {
            if (System.currentTimeMillis() - start > 10 * 1000) {
                result = false;
                break;
            }
            Thread.sleep(100);

            file = new File(destination);
            if (file.exists()) {
                break;
            }
        }
        return result;
    }

    public static boolean captureThumbnail(String ffmpegPath,
            String sourceFile, String destination, String aspectratio,
            boolean isSynchronized) throws IOException, InterruptedException {
        return captureThumbnail(ffmpegPath, sourceFile, destination,
                aspectratio, null, isSynchronized);
    }
}
FFMpegUtils
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.xml.bind.JAXB;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class FtpUtils {
    Logger logger = LoggerFactory.getLogger(getClass());
    private interface __ObjectConverter {
        void objectToStream(Object object, OutputStream stream) throws IOException;
    }

    private static class __JAXBConverter implements __ObjectConverter {
        private static __ObjectConverter converter = null;

        @Override
        public void objectToStream(Object object, OutputStream stream) {
            JAXB.marshal(object, stream);
        }

        public static __ObjectConverter getInstance() {
            return converter == null ? new __JAXBConverter() : converter;
        }
    }

    private static class __JsonConverter implements __ObjectConverter {
        private static __ObjectConverter converter = null;

        @Override
        public void objectToStream(Object object, OutputStream stream) throws IOException {
            String json = JsonObjUtil.ObjToJson(object);
            try (OutputStreamWriter writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
                writer.write(json);
                writer.flush();
            }
        }

        public static __ObjectConverter getInstance() {
            return converter == null ? new __JsonConverter() : converter;
        }
    }

    public static class FtpHolder {
        private String host;
        private int port;
        private String user;
        private String password;
        private String relativePath;
        private String fileName;
        private boolean passiveMode = true;
        private String encoding = "UTF-8";
        private FTPClient ftp;

        @Override
        public boolean equals(Object o) {
            if (o instanceof FtpHolder) {
                FtpHolder holder = (FtpHolder) o;
                return host != null && host.equals(holder.getHost()) && port == holder.getPort() && user != null
                        && user.equals(holder.getUser()) && password != null && password.equals(holder.getPassword());
            } else {
                return false;
            }
        }

        public boolean checkConnection() {
            try {
                int np = ftp.noop();
                return np >= 200 && np < 300;
            } catch (Exception e) {
                try {
                    ftp.disconnect();
                } catch (Exception e1) {
                }
                try {
                    if (ftp == null) {
                        ftp = new FTPClient();
                    }
                    ftp.setControlEncoding("UTF-8");
                    ftp.connect(host, port);
                    return ftp.login(user, password);
                } catch (IOException e1) {
                    return false;
                }
            }
        }

        public boolean checkFile() throws IOException {
            if(checkConnection()){
                FTPFile[] ftpFiles = ftp.listFiles(relativePath + fileName);
                return !ObjectUtils.isEmpty(ftpFiles);
            }

            return false;
        }

        /**
         * @return the host
         */
        public String getHost() {
            return host;
        }

        /**
         * @param host
         *            the host to set
         */
        public void setHost(String host) {
            this.host = host;
        }

        /**
         * @return the port
         */
        public int getPort() {
            return port;
        }

        /**
         * @param port
         *            the port to set
         */
        public void setPort(int port) {
            this.port = port;
        }

        /**
         * @return the user
         */
        public String getUser() {
            return user;
        }

        /**
         * @param user
         *            the user to set
         */
        public void setUser(String user) {
            this.user = user;
        }

        /**
         * @return the password
         */
        public String getPassword() {
            return password;
        }

        /**
         * @param password
         *            the password to set
         */
        public void setPassword(String password) {
            this.password = password;
        }

        /**
         * @return the ftp
         */
        public FTPClient getFtp() {
            return ftp;
        }

        /**
         * @param ftp
         *            the ftp to set
         */
        public void setFtp(FTPClient ftp) {
            this.ftp = ftp;
        }

        public boolean makeDirs(String fileName) throws IOException {
            fileName = fileName.replaceAll("^ftp\\:\\/\\/[^\\/]*", "").replaceAll("^\\/", "").replaceAll("[^\\/]*$", "")
                    .replaceAll("\\/$", "");
            return makePathDirs(fileName);
        }

        public boolean makeDirs() throws IOException {
            return makePathDirs(relativePath == null ? "" : relativePath.replaceAll("[\\\\\\/]$", ""));
        }

        public boolean makePathDirs(String path) throws IOException {
            if (path.length() > 0) {
                String[] paths = path.split("\\/");
                ftp.changeWorkingDirectory("/");
                for (String temp : paths) {
                    if (!ftp.changeWorkingDirectory(temp)) {
                        if (!ftp.makeDirectory(temp)) {
                            return false;
                        }
                        if (!ftp.changeWorkingDirectory(temp)) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        public String toUrl() {
            StringBuilder sb = new StringBuilder();
            sb.append("ftp://");
            if (StringUtils.hasText(user)) {
                sb.append(user);
                if (StringUtils.hasText(password)) {
                    sb.append(":");
                    sb.append(password);
                }
                sb.append("@");
            }
            sb.append(host);
            if (this.port > 0 && this.port != 21) {
                sb.append(":");
                sb.append(port);
            }
            String relaPath = relativePath.replaceAll("^[\\\\\\/]+|[\\\\\\/]+$", "");
            if (StringUtils.hasText(relaPath)) {
                sb.append("/");
                sb.append(relaPath);
            }
            if (StringUtils.hasText(fileName)) {
                sb.append("/");
                sb.append(fileName.replaceAll("^[\\\\\\/]+|[\\\\\\/]+$", ""));
            }
            return sb.toString();
        }

        public boolean changeDir() throws IOException {
            return changeDir(this.relativePath);
        }

        public boolean changeDir(String relativePath) throws IOException {
            ftp.changeWorkingDirectory("/");
            if (StringUtils.isEmpty(relativePath)) {
                return true;
            }
            relativePath = relativePath.replaceAll("^[\\\\\\/]+|[\\\\\\/]+$", "");
            if (StringUtils.isEmpty(relativePath)) {
                return true;
            }
            for (String path : relativePath.split("[\\\\\\/]")) {
                if (!ftp.changeWorkingDirectory(path)) {
                    return false;
                }
            }
            return true;
        }

        public String getRelativePath() {
            return relativePath;
        }

        public void setRelativePath(String relativePath) {
            this.relativePath = relativePath;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public boolean isPassiveMode() {
            return passiveMode;
        }

        public void setPassiveMode(boolean passiveMode) {
            this.passiveMode = passiveMode;
        }

        public String getEncoding() {
            return encoding;
        }

        public void setEncoding(String encoding) {
            this.encoding = encoding;
        }
    }

    private static List<FtpHolder> holders = new ArrayList<FtpUtils.FtpHolder>();

    public static FtpHolder urlToFtp(String ftpUrl) {
        // 扒出用户名口令
        FtpHolder result = new FtpHolder();
        String user = ftpUrl.replaceAll("(?i)^(ftp\\:\\/\\/)([\\w\\-\\_\\!\\~\\#\\$\\%\\^\\&\\:]*\\@)?(.*)$", "$2").replaceAll("\\@$", "");
        String[] up = user.split("\\:");
        result.setUser(up[0]);
        if (up.length > 1) {
            result.setPassword(up[1]);
        } else {
            result.setPassword("");
        }
        if (StringUtils.isEmpty(user)) {
            // result.setUser("anonymous");
            // result.setPassword("tester@cdv.com");
            result.setUser("cdv");
            result.setPassword("LBIvlrUMMw");
        }

        // 脱去用户、口令信息
        ftpUrl = ftpUrl.replaceAll("(?i)^(ftp\\:\\/\\/)([\\w\\-\\_\\!\\~\\#\\$\\%\\^\\&\\:]*\\@)?(.*)$", "$1$3");
        // 相对路径和文件名分析
        String pathFile = ftpUrl.replaceAll("(?i)^(ftp\\:\\/\\/)[^\\/]+", "");
        result.setRelativePath(pathFile.replaceAll("[^\\\\\\/]+$", ""));
        result.setFileName(pathFile.replaceAll("^.*[\\\\\\/]", ""));

        // 扒出ip和端口
        ftpUrl = ftpUrl.replaceAll("ftp\\:\\/\\/([^\\/]+)(\\/.*)?", "$1");
        String[] hp = ftpUrl.split("\\:");
        result.setHost(hp[0]);
        try {
            result.setPort(Integer.parseInt(hp[1]));
        } catch (Throwable t) {
            result.setPort(21);
        }
        return result;
    }

    public static FtpHolder getFtpClient(String fileName) {
        FtpHolder result = FtpUtils.urlToFtp(fileName);
        for (FtpHolder holder : holders) {
            if (result.equals(holder)) {
                return holder;
            }
        }
        return result;
    }

    public static void jaxbObject2Ftp(Object jaxbObj, String fileName, boolean passiveMode) throws IOException {
        saveObject2Ftp(jaxbObj, fileName, passiveMode, __JAXBConverter.getInstance());
    }

    public static void jsonObject2Ftp(Object jsonObj, String fileName, boolean passiveMode) throws IOException {
        saveObject2Ftp(jsonObj, fileName, passiveMode, __JsonConverter.getInstance());
    }

    private static void saveObject2Ftp(Object object, String fileName, boolean passiveMode, __ObjectConverter converter)
            throws IOException {
        FtpHolder ftp = FtpUtils.getFtpClient(fileName);
        if (ftp.checkConnection()) {
            if (passiveMode) {
                ftp.getFtp().enterLocalPassiveMode();
            } else {
                ftp.getFtp().enterLocalActiveMode();
            }
            if (ftp.makeDirs(fileName)) {
                String temp = fileName.replaceAll("^.*\\/", "");
                try (OutputStream os = ftp.getFtp().storeFileStream(temp)) {
                    converter.objectToStream(object, os);
                    os.flush();
                }
            } else {
                throw new IOException("目录创建失败");
            }
        } else {
            throw new IOException("连接到ftp服务器出错");
        }
    }

    public static void copyFile2Ftp(String fileName, InputStream input, boolean passiveMode) throws IOException {
        FtpHolder ftp = FtpUtils.getFtpClient(fileName);
        if (ftp.checkConnection()) {
            if (passiveMode) {
                ftp.getFtp().enterLocalPassiveMode();
            } else {
                ftp.getFtp().enterLocalActiveMode();
            }
            if (ftp.makeDirs(fileName)) {
                String temp = fileName.replaceAll("^.*\\/", "");
                ftp.getFtp().storeFile(temp, input);
            } else {
                throw new IOException("目录创建失败");
            }
        } else {
            throw new IOException("连接到ftp服务器出错");
        }
    }

    public static void copyFile2Ftp(FtpHolder ftp, String fileName, InputStream input, boolean passiveMode)
            throws IOException {
        if (ftp.checkConnection()) {
            if (passiveMode) {
                ftp.getFtp().enterLocalPassiveMode();
            } else {
                ftp.getFtp().enterLocalActiveMode();
            }
            if (ftp.makeDirs()) {
                String temp = StringUtils.hasText(fileName) ? fileName.replaceAll("^.*\\/", "") : ftp.getFileName();
                ftp.getFtp().setFileType(FTPClient.BINARY_FILE_TYPE);
                ftp.getFtp().storeFile(temp, input);
            } else {
                throw new IOException("目录创建失败");
            }
        } else {
            throw new IOException("连接到ftp服务器出错");
        }
    }

    public static void chunAnCopyFile2Ftp(FtpHolder ftp, String fileName, InputStream input, boolean passiveMode)
            throws IOException {
        if (ftp.checkConnection()) {
            if (passiveMode) {
                ftp.getFtp().enterLocalPassiveMode();
            } else {
                ftp.getFtp().enterLocalActiveMode();
            }
            if (ftp.makeDirs()) {
                String temp = StringUtils.hasText(fileName) ? fileName.replaceAll("^.*\\/", "") : ftp.getFileName();
                ftp.getFtp().setFileType(FTP.BINARY_FILE_TYPE);
                ftp.getFtp().storeFile(temp, input);
            } else {
                throw new IOException("目录创建失败");
            }
        } else {
            throw new IOException("连接到ftp服务器出错");
        }
    }

    public static void chunAnCopyFile2Ftp(FtpHolder ftp, String fileName, InputStream input, boolean passiveMode,
            String pathName) throws IOException {
        if (ftp.checkConnection()) {
            if (passiveMode) {
                ftp.getFtp().enterLocalPassiveMode();
            } else {
                ftp.getFtp().enterLocalActiveMode();
            }
            // 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
            // if (FTPReply.isPositiveCompletion(ftp.getFtp().sendCommand("OPTS
            // UTF8",
            // "ON"))) {
            // LOCAL_CHARSET = "UTF-8";
            // SERVER_CHARSET = "UTF-8";
            // }
            ftp.getFtp().makeDirectory(pathName);
            ftp.getFtp().changeWorkingDirectory(pathName);
            if (ftp.makeDirs()) {
                String temp = StringUtils.hasText(fileName) ? fileName.replaceAll("^.*\\/", "") : ftp.getFileName();
                ftp.getFtp().setFileType(FTP.BINARY_FILE_TYPE);
                ftp.getFtp().storeFile(temp, input);
            } else {
                throw new IOException("目录创建失败");
            }
        } else {
            throw new IOException("连接到ftp服务器出错");
        }
    }
}
FtpUtil
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.springframework.util.StreamUtils;

/*
 * 依赖org.apache.commons.logging.LogFactory
 */
public class Unzip {
    private static FileSystemManager manager = null;

    private static void init() throws FileSystemException {
        if (manager == null) {
            manager = VFS.getManager();
        }
    }

    public static List<String> unzipFile(String zipFileName,
            String targetBaseDirName) throws IOException {
        return unzipFile(zipFileName, targetBaseDirName, Charset.forName("GBK"));
    }

    public static List<String> unzipFile(URI fileUri, String targetBaseDirName)
            throws IOException {
        return unzipFile(new File(fileUri), targetBaseDirName);
    }

    public static List<String> unzipFile(File file, String targetBaseDirName)
            throws IOException {
        return unzipFile(file, targetBaseDirName, Charset.forName("GBK"));
    }

    public static List<String> unzipFile(String zipFileName,
            String targetBaseDirName, Charset charset) throws IOException {
        File f = null;
        try{
            f = new File(new URI(zipFileName));
        }catch(URISyntaxException e){
            f = new File(zipFileName);
        }
        return unzipFile(f, targetBaseDirName, charset);
    }

    public static List<String> unzipFile(URI fileUri, String targetBaseDirName,
            Charset charset) throws IOException {
        return unzipFile(new File(fileUri), targetBaseDirName, charset);
    }

    public static List<String> unzipFile(File file, String targetBaseDirName,
            Charset charset) throws IOException {
        init();
        targetBaseDirName = targetBaseDirName.replaceAll("[\\\\\\/]+$", "")
                + "/";
        // 根据ZIP文件创建ZipFile对象
        try (ZipFile zipFile = new ZipFile(file, charset)) {

            // 获取ZIP文件里所有的entry
            Enumeration<? extends ZipEntry> entrys = zipFile.entries();
            // 遍历所有entry
            List<String> result = new ArrayList<String>();
            while (entrys.hasMoreElements()) {
                ZipEntry entry = entrys.nextElement();
                // 获得entry的名字
                String entryName = entry.getName();
                String targetFileName = targetBaseDirName + entryName;
                targetFileName = targetFileName.replaceAll("\\%", "%25");
                FileObject fo = manager.resolveFile(targetFileName);
                if (entry.isDirectory()) {
                    // 如果entry是一个目录,则创建目录
                    fo.createFolder();
                } else {
                    //只记录文件
                    result.add(targetFileName);
                    try (OutputStream os = fo.getContent().getOutputStream()) {
                        try (InputStream is = zipFile.getInputStream(entry)) {
                            StreamUtils.copy(is, os);
                        }
                    }
                }
                fo.getContent().setLastModifiedTime(entry.getTime());
            }
            return result;
        }
    }
ZIP
/**
 * 获取操作系统信息
 */
public final class OSInfo {

    private static final String OS_NAME = System.getProperty("os.name").toLowerCase();

    public static String getOSName() {
        return System.getProperty("os.name");
    }

    public static String getOSVersion() {
        return System.getProperty("os.version");
    }

    public static boolean isWindows() {
        return OS_NAME.contains("windows");
    }

    public static boolean isMac() {
        return OS_NAME.contains("mac") && OS_NAME.indexOf("os") > 0 && !OS_NAME.contains("x");
    }

    public static boolean isLinux() {
        return OS_NAME.contains("linux");
    }
}
OSInfo

 

posted @ 2020-03-26 16:50  凉城  阅读(337)  评论(0编辑  收藏  举报