java工具类中常用工具

public class FunUtils {

    /**
     * 获取系统时间 yyyy-MM-dd HH:mm:ss
     * new Date() --> mysql dateTime  会在数据库自动解析为 yyyy-MM-dd HH:mm:ss 保存
     **/
    public static String getSysDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sysTime = df.format(new Date());
        return sysTime;
    }

 

    /***
     *  重命名str;
     *   如:用日期时间(或UUID重新命名)上传的文件名称:防止同名文件被覆盖
     **/
    public static String getNewStr(String str) {

        String datetimeFormat = "yyyy-MM-dd--HH-mm-ss";
        SimpleDateFormat sdf = new SimpleDateFormat(datetimeFormat);
        String curTime = sdf.format(new Date());
        String newStr = curTime + "_" + str;
        //String newStr = UUID.randomUUID().toString() + "_" + originalFilename;
        return newStr;
    }

    /***
     * 1.UUID 获取 32位 唯一标识
     * 2.RandomStringUtils.randomAlphanumeric(6)
     * @return
     */
    public static String getNewStrUUID() {
        String newStr = UUID.randomUUID().toString();
        return newStr;
    }

    /**
     * 获取  时间
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDateLong(Date date) {
        // Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(date);
        return dateString;
    }

    /**
     * 获取现在时间
     *
     * @return 返回短时间字符串格式yyyy-MM-dd
     */
    public static String getStringDateShort(Date date) {
        // Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);
        return dateString;
    }


    /**
     * 删除指定目录及其该目录下所有文件
     * 先删文件--》再删目录(目录不为空,不可删除)
     * @param filePath  要删除的目录的路径  .../lecturerImg\lisi\lisi_img.png
     */
    //不能注入,使用java 获取
    @Value(value = "${web.uploadFile-pathPre}")
    static String serverPathPre;
    @Value(value = "${local.uploadFile-pathPre}")
    static String localPathPre;

    public static Boolean deleteFileByPath(String filePath) {
        filePath = filePath.substring(0, filePath.lastIndexOf("\\") + 1);
        String regex = "[\\/\\s]+";
        if (filePath == null || filePath.equals("") || filePath.matches(regex)) {
            System.out.println(filePath + "资源不存在");
            return false;
        } else {
            filePath = localPathPre + filePath;
            System.out.println(filePath + "资源存在");
            return true;
        }

    }

    /**
     * byte[]  转 String   util
     */
    public static String byteArrayToStr(byte[] byteArray, String characterEncoding) {
        String str = null;
        if (byteArray == null) {
            return null;
        }
        try {
            str = new String(byteArray, characterEncoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * String 转 byte[]    util
     */
    public static byte[] strToByteArray(String str, String characterEncoding) {
        byte[] byteArray = new byte[0];
        if (str == null) {
            return null;
        }
        try {
            byteArray = str.getBytes(characterEncoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return byteArray;
    }

    /**
     * 对象转Map
     */
    public static Map ConvertObjToMap(Object obj) {
        Map<String, Object> reMap = new HashMap<String, Object>();
        if (obj == null) {
            return null;
        }
        Field[] fields = obj.getClass().getDeclaredFields();
        try {
            for (int i = 0; i < fields.length; i++) {
                try {
                    Field f = obj.getClass().getDeclaredField(fields[i].getName());
                    f.setAccessible(true);
                    Object o = f.get(obj);
                    reMap.put(fields[i].getName(), o);
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return reMap;
    }


    /**byte[] 与 file之间的相互转化  util**/
    /**
     * 获得指定文件的byte数组
     * 存入数据库 大文本字段
     **/
    public static byte[] fileToByteArray(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 根据byte数组,生成文件
     * 存入临时目录:前台读取显示
     **/
    public static void byteArrayToFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            //&& dir.isDirectory()
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file = new File(filePath + "\\" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }


    /**
     * 获取Multipart文件格式的后缀(不含点)
     */
    public static String getFileSuffix(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extString = fileName.substring(fileName.lastIndexOf(".") + 1);
        return extString;
    }

    /**
     * 生成订单编号 格式:yyyyMMddHHmmssSS+随机5位数字
     * @return
     */
    public static String createOrderNo() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = fmt.format(new Date()) + (int) ((Math.random() * 9 + 1) * 10000);
        return s;
    }

    /**
     * 查询本机外网ip地址
     * @return
     */
    public static String getV4IP() {
        String ip = "";
        String chinaz = "http://ip.chinaz.com";

        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
            //System.out.println(inputLine.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
        Matcher m = p.matcher(inputLine.toString());
        if (m.find()) {
            String ipstr = m.group(1);
            ip = ipstr;
            //System.out.println(ipstr);
        }
        return ip;
    }

    /**
     * 获取http请求中的xml数据字符串
     * @param request
     * @return
     */
    public static String getXmlString(HttpServletRequest request) {
        BufferedReader reader = null;
        String line = "";
        String xmlString = null;
        try {
            reader = request.getReader();
            StringBuffer inputString = new StringBuffer();

            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            xmlString = inputString.toString();
        } catch (Exception e) {

        }

        return xmlString;
    }

    /**
     * 将字符串中的汉字转换为指定的字符
     *
     * @param source
     * @param replacement
     * @return
     */
    public static String replaceChinese(String source, String replacement) {
        if (StringUtils.isBlank(source)) {
            return null;
        }
        if (replacement == null) {
            replacement = "";
        }
        String reg = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(reg);
        Matcher mat = pat.matcher(source);
        String repickStr = mat.replaceAll(replacement);
        return repickStr;
    }

    public static String replaceEngMonth(String original) {
        if (StringUtils.isNotBlank(original)) {
            return original.toLowerCase().replaceAll("january", "01").replaceAll("jan", "01")
                    .replaceAll("february", "02").replaceAll("feb", "02")
                    .replaceAll("march", "03").replaceAll("mar", "03")
                    .replaceAll("april", "04").replaceAll("apr", "04")
                    .replaceAll("may", "05").replaceAll("may", "05")
                    .replaceAll("june", "06").replaceAll("jun", "06")
                    .replaceAll("july", "07").replaceAll("jul", "07")
                    .replaceAll("august", "08").replaceAll("aug", "08")
                    .replaceAll("september", "09").replaceAll("sep", "09")
                    .replaceAll("october", "10").replaceAll("oct", "10")
                    .replaceAll("november", "11").replaceAll("nov", "11")
                    .replaceAll("december", "12").replaceAll("dec", "12");
        }
        return null;
    }

    public static String getRequestIpV4(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {

            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {

            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {

            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值