简记 java工具类(2)

1.字符集工具类:

import lombok.extern.slf4j.Slf4j;
import java.io.*;

/**
 *
 * 字符集工具类
 */
@Slf4j
public class MyCharsetUtil {

    /** 7位ASCII字符,也叫作ISO646-US、Unicode字符集的基本拉丁块 */
    public static final String US_ASCII = "US-ASCII";

    /** ISO 拉丁字母表 No.1,也叫作 ISO-LATIN-1 */
    public static final String ISO_8859_1 = "ISO-8859-1";

    /** 8 位 UCS 转换格式 */
    public static final String UTF_8 = "UTF-8";

    /** 16 位 UCS 转换格式,Big Endian(最低地址存放高位字节)字节顺序 */
    public static final String UTF_16BE = "UTF-16BE";

    /** 16 位 UCS 转换格式,Little-endian(最高地址存放低位字节)字节顺序 */
    public static final String UTF_16LE = "UTF-16LE";

    /** 16 位 UCS 转换格式,字节顺序由可选的字节顺序标记来标识 */
    public static final String UTF_16 = "UTF-16";

    /** 中文超大字符集 */
    public static final String GBK = "GBK";

    /**
     * 将字符编码转换成US-ASCII码
     */
    public String toASCII(String str) throws UnsupportedEncodingException {
        return this.changeCharset(str, US_ASCII);
    }
    /**
     * 将字符编码转换成ISO-8859-1码
     */
    public String toISO_8859_1(String str) throws UnsupportedEncodingException{
        return this.changeCharset(str, ISO_8859_1);
    }
    /**
     * 将字符编码转换成UTF-8码
     */
    public String toUTF_8(String str) throws UnsupportedEncodingException{
        return this.changeCharset(str, UTF_8);
    }
    /**
     * 将字符编码转换成UTF-16BE码
     */
    public String toUTF_16BE(String str) throws UnsupportedEncodingException{
        return this.changeCharset(str, UTF_16BE);
    }
    /**
     * 将字符编码转换成UTF-16LE码
     */
    public String toUTF_16LE(String str) throws UnsupportedEncodingException{
        return this.changeCharset(str, UTF_16LE);
    }
    /**
     * 将字符编码转换成UTF-16码
     */
    public String toUTF_16(String str) throws UnsupportedEncodingException{
        return this.changeCharset(str, UTF_16);
    }
    /**
     * 将字符编码转换成GBK码
     */
    public String toGBK(String str) throws UnsupportedEncodingException{
        return this.changeCharset(str, GBK);
    }

    /**
     * 字符串编码转换的实现方法
     * @param str  待转换编码的字符串
     * @param newCharset 目标编码
     * @return
     * @throws UnsupportedEncodingException
     */
    public String changeCharset(String str, String newCharset)
            throws UnsupportedEncodingException {
        if (str != null) {
            //用默认字符编码解码字符串。
            byte[] bs = str.getBytes();
            //用新的字符编码生成字符串
            return new String(bs, newCharset);
        }
        return null;
    }
    /**
     * 字符串编码转换的实现方法
     * @param str  待转换编码的字符串
     * @param oldCharset 原编码
     * @param newCharset 目标编码
     * @return
     * @throws UnsupportedEncodingException
     */
    public String changeCharset(String str, String oldCharset, String newCharset)
            throws UnsupportedEncodingException {
        if (str != null) {
            //用旧的字符编码解码字符串。解码可能会出现异常。
            byte[] bs = str.getBytes(oldCharset);
            //用新的字符编码生成字符串
            return new String(bs, newCharset);
        }
        return null;
    }



    public static String getStrCharset(String str) {
        String encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode ="ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }


   /*public static String getFileCharset(File file)  {
        String code = null;
        BufferedInputStream bin = null;
        try {
            bin =new BufferedInputStream(new FileInputStream(file));
            int p = (bin.read() << 8) + bin.read();
            //其中的 0xefbb、0xfffe、0xfeff、0x5c75这些都是这个文件的前面两个字节的16进制数
            switch (p) {
                case 0xefbb:
                    code = "UTF-8";
                    break;
                case 0xfffe:
                    code = "Unicode";
                    break;
                case 0xfeff:
                    code = "UTF-16BE";
                    break;
                case 0x5c75:
                    code = "ANSI|ASCII";
                    break;
                default:
                    code = "GBK";
            }
        }catch (IOException e){
            log.error("getFileCharset error",e);
        }finally {
            if(bin!=null){
                try {
                    bin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return code;

    }*/







    /**
     * 判断文本文件的字符集,文件开头三个字节表明编码格式。
     * @param file
     * @return
     * @throws Exception
     * @throws Exception
     */
    public static String getFileCharset(File file) {
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        try {
            boolean checked = false;
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            bis.mark(100);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1) {
                bis.close();
                return charset; // 文件编码为 ANSI
            } else if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "UTF-16LE"; // 文件编码为 Unicode
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
                charset = "UTF-16BE"; // 文件编码为 Unicode big endian
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF-8"; // 文件编码为 UTF-8
                checked = true;
            }
            bis.reset();
            if (!checked) {
                while ((read = bis.read()) != -1) {
                    if (read >= 0xF0) {
                        break;
                    }
                    if (0x80 <= read && read <= 0xBF) {// 单独出现BF以下的,也算是GBK
                        break;
                    }
                    if (0xC0 <= read && read <= 0xDF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {// 双字节 (0xC0 - 0xDF)
                            // (0x80 - 0xBF),也可能在GB编码内
                            continue;
                        }else {
                            break;
                        }
                    } else if (0xE0 <= read && read <= 0xEF) { // 也有可能出错,但是几率较小
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = bis.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return charset;
    }

    public static String changeFileCharset(String inPath,String outPath,String oldCharset, String newCharset) throws Exception {
        // 以GBK格式读取文件
        FileInputStream fis = new FileInputStream(inPath);
        InputStreamReader isr = new InputStreamReader(fis, oldCharset);
        BufferedReader br = new BufferedReader(isr);
        String str = null;
        // 创建StringBuffer字符串缓存区
        StringBuffer sb = new StringBuffer();
        // 通过readLine()方法遍历读取文件
        while ((str = br.readLine()) != null) {
            // 使用readLine()方法无法进行换行,需要手动在原本输出的字符串后面加"\n"或"\r"
            str += "\n";
            sb.append(str);
        }
        // 以UTF-8文件写入
        String str2 = sb.toString();
        FileOutputStream fos = new FileOutputStream(outPath, false);
        OutputStreamWriter osw = new OutputStreamWriter(fos, newCharset);
        osw.write(str2);
        osw.flush();
        osw.close();
        fos.close();
        br.close();
        isr.close();
        fis.close();
        return "文件生成成功";
    }





}

2. 日期工具类:

import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 时间工具类
 **/
@Slf4j
public class DatesUtil {

    /**
     * 时间格式化pattern
     */
    public static final String FORMAT_PATTERN_DATE = "yyyy-MM-dd";
    public static final String FORMAT_PATTERN_TIME = "HH:mm:ss";
    public static final String FORMAT_PATTERN_DATE_TIME = FORMAT_PATTERN_DATE + " " + FORMAT_PATTERN_TIME;

    /**
     * 计算两个时间差值的时分秒形式
     *
     */
    public static String getGapTime(long time) {
        int ten = Integer.parseInt("10");
        //计算小时
        long hours = time / (1000 * 60 * 60);
        //计算分钟        (总毫秒数-小时占毫秒数)/每一分钟的毫秒数
        long minutes = (time - hours * (1000 * 60 * 60)) / (1000 * 60);

        long second = (time - hours * (1000 * 60 * 60) - minutes * (1000 * 60)) / 1000;

        long millisecond = time - hours * (1000 * 60 * 60) - minutes * (1000 * 60) - second * 1000;

        StringBuffer diffTime = new StringBuffer("");

        if (minutes < ten) {
            if (second < ten) {
                diffTime.append(hours).append("时0").append(minutes).append("分0").append(second).append("秒").append(millisecond);
            } else {
                diffTime.append(hours).append("时0").append(minutes).append("分").append(second).append("秒").append(millisecond);
            }

        } else {
            if (second < ten) {
                diffTime.append(hours).append("时").append(minutes).append("分0").append(second).append("秒").append(millisecond);
            } else {
                diffTime.append(hours).append("时").append(minutes).append("分").append(second).append("秒").append(millisecond);
            }
        }

        return diffTime.toString();
    }

    /**
     * 包含首尾天数
     * 时间格式是: yyyy-MM-dd HH:mm:ss
     */
    public static Date getDayFromNow(Date now, int days) {
        DateFormat dateFormat = new SimpleDateFormat(FORMAT_PATTERN_DATE_TIME);
        try {
            Date start = dateFormat.parse(dateFormat.format(now));
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            tempStart.add(Calendar.DAY_OF_MONTH, days);
            return tempStart.getTime();
        } catch (Exception e) {
            log.warn("getDayFromNow ==> For date:|{}| days:|{}| exception:",now,days,e);
        }
        return null;
    }

    /**
     * 获取两个日期之间的所有日期  
     * @param startTime 开始日期 
     * @param endTime  结束日期 
     * 包含首尾天数
     */
    public static List<String> getDays(Date startTime, Date endTime) {
        // 返回的日期集合
        List<String> days = new ArrayList<String>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(dateFormat.format(startTime));
            Date end = dateFormat.parse(dateFormat.format(endTime));
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);
            // 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * 格式化时间
     */
    public static String formatDate(Date date, String pattern) {
        if (null == date || null == pattern || pattern.isEmpty()){
            return "";
        }
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime dateTime = ZonedDateTime.ofInstant(date.toInstant(), zoneId);
        return DateTimeFormatter.ofPattern(pattern).format(dateTime);
    }

    /**
     * 格式化时间为 [yyyy-MM-dd yyyy:MM:dd]
     **/
    public static String formatDate(Date date) {
       return formatDate(date,FORMAT_PATTERN_DATE_TIME);
    }

    /**
     * 格式化字符串成为时间
     * "yyyy-MM-dd hh:mm:ss"
     *
     * @param date
     * @return
     */
    public static Date parseDate(String date, String pattern) {
        SimpleDateFormat sim = new SimpleDateFormat(pattern);
        try {
            return sim.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取指定时间的日初和日暮
     *
     * @param date
     * @return
     */
    public static Date[] getTheDay(Date date) {
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String beforeDay = sim.format(date.getTime()).split(" ")[0];
        StringBuilder sbStart = new StringBuilder(beforeDay);
        sbStart.append(" 00:00:00");
        StringBuilder sbEnd = new StringBuilder(beforeDay);
        sbEnd.append(" 23:59:59");
        try {
            Date startDate = sim.parse(sbStart.toString());
            Date endDate = sim.parse(sbEnd.toString());
            return new Date[]{startDate, endDate};
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取指定天的凌晨时间戳
     *
     * @param date
     * @return
     */
    public static long getTheDayTime(Date date) {
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateStr = sim.format(date);
        StringBuilder dateStart = new StringBuilder(dateStr.split(" ")[0]);
        dateStart.append(" 00:00:00");
        Date parseDate = parseDate(dateStart.toString(), "yyyy-MM-dd hh:mm:ss");
        return Objects.requireNonNull(parseDate).getTime();
    }

    /**
     * 获取上个月的周期
     * yyyy-MM-dd
     *
     * @param date
     * @return
     */
    public static Date[] getLastMonth(Date date) {
        Calendar cale = new GregorianCalendar();
        cale.setTime(date);
        cale.add(Calendar.MONTH, -1);
        // 获取当月第一天和最后一天
        Date firstday, lastday;
        // 获取本月的第一天
        cale.set(Calendar.DAY_OF_MONTH, 1);
        firstday = cale.getTime();
        // 获取前月的最后一天
        cale = Calendar.getInstance();
        cale.set(Calendar.DAY_OF_MONTH, 0);
        lastday = cale.getTime();
        return new Date[]{firstday, lastday};
    }

    /**
     * 获取上个周的周期
     * yyyy-MM-dd
     *
     * @param date
     * @return
     */
    public static Date[] getLastWeek(Date date) {
        Calendar cale = new GregorianCalendar();
        cale.setTime(date);
        cale.add(Calendar.WEEK_OF_MONTH, -1);
        // 获取当周第一天和最后一天
        Date firstday, lastday;
        // 获取本周的第一天
        cale.set(Calendar.DAY_OF_WEEK, 2);
        firstday = cale.getTime();
        // 获取本周的最后一天
        cale.setTime(date);
        cale.set(Calendar.DAY_OF_WEEK, 1);
        lastday = cale.getTime();
        return new Date[]{firstday, lastday};
    }

    /**
     * 得到本周周日
     *
     * @return yyyy-MM-dd
     */
    public static Date getSundayOfThisWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayOfWeek == 0) {
            dayOfWeek = 7;
        }
        c.add(Calendar.DATE, -dayOfWeek + 7);
        return c.getTime();
    }

    /**
     * 得到本周周末
     *
     * @return yyyy-MM-dd
     */
    public static Date getMondayOfThisWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayOfWeek == 0) {
            dayOfWeek = 7;
        }
        c.add(Calendar.DATE, -dayOfWeek + 1);
        return c.getTime();
    }

    /**
     * 得到今天是周几
     *
     * @return yyyy-MM-dd
     */
    public static int getTheDayOfWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.DAY_OF_WEEK) - 1;
    }


    /**
     * 得到今天是周几
     *
     * @return yyyy-MM-dd
     */
    public static int getTheDayOfMonth(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.DAY_OF_MONTH);
    }


    public static Date getNowTime() {
        //当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date nowtime = null;
        try {
            nowtime = df.parse(df.format(new Date()));
        } catch (ParseException e) {
            log.error("{}", e);
        }
        return nowtime;
    }


    public static Date getNowTimeNoHMD() {
        //当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        Date nowtime = null;
        try {
            nowtime = df.parse(df.format(new Date()));
        } catch (ParseException e) {
            log.error("{}", e);
        }
        return nowtime;
    }


    public static Long dateStrToSeconds(String dateStr) {

        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date parseDate = null;
        try {
            parseDate = sim.parse(dateStr);
            return TimeUnit.MILLISECONDS.toSeconds(parseDate.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;

    }

    public static Long dateToSeconds(Date parseDate) {
         return TimeUnit.MILLISECONDS.toSeconds(parseDate.getTime());
    }



    /**
     * 获取指定日期的最小时间
     * @param date  指定日期
     * @return java.util.Date
     */
    public static Date getStartOfDay(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()),ZoneId.systemDefault());
        LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
        return Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取指定日期的最大时间
     * @param date  指定日期
     * @return java.util.Date
     */
    public static Date getEndOfDay(Date date) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()),ZoneId.systemDefault());
        LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
        return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
    }


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值