开发常用工具类

目录

1、时间相关的

2、文件相关


出来工作一段时间了,这里总结一下这3个月工作中使用过的工具类,以备以后使用,也分享给大家。

有时间会更新.....


1、时间相关的




import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

	private final static String FORMATSTRING = "yyyy-MM-dd HH:mm:ss";

	public static String getTime(long ts) {
		SimpleDateFormat formatter = new SimpleDateFormat(FORMATSTRING);
		Date d = new Date(ts);
		return formatter.format(d);
	}

	public static long stringToLong(String strTime)
 			throws ParseException {
 		Date date = stringToDate(strTime);
 		if (date == null) {
 			return 0;
 		} else {
 			long currentTime = date.getTime();
 			return currentTime;
 		}
 	}

	public static Date stringToDate(String strTime)
 			throws ParseException {
 		SimpleDateFormat formatter = new SimpleDateFormat(FORMATSTRING);
 		Date date = null;
 		date = formatter.parse(strTime);
 		return date;
 	}

	/**
	 * 日期范围查询,开始日期的处理
	 * 将所传日期置为当天的0点
	 * @param startDate
	 * @return
	 */
 	public static Date convertQueryStartDate(String startDate,String parsePattern) throws ParseException {
		Date date = null;
		date = stringToDate(startDate,parsePattern);

		Date truncDate = dateTruncForType(date,1);
		return truncDate;
	}

	/**
	 * 日期范围查询,开始日期的处理
	 * type为日期的格式,年为2020 月为2020-02 日为2020-02-01
	 * @param startDate
	 * @param type 1年 2月 3日
	 * @return
	 * @throws ParseException
	 */
	public static Date convertQueryStartDate(String startDate,int type) throws ParseException {
		Date date = getFirstDateByType(startDate,type);
		Date truncDate = dateTruncForType(date,1);
		return truncDate;
	}

	/**
	 * 日期范围查询,开始日期的处理
	 * type为日期的格式,年为2020 月为2020-02 日为2020-02-01
	 * @param startDate
	 * @param type 1年 2月 3日
	 * @return
	 * @throws ParseException
	 */
	public static Date convertQueryEndDate(String startDate,int type) throws ParseException {
		Date date  = getLastDateByType(startDate,type);
		Date nextDay = addDays(date,1);
		return dateTruncForType(nextDay,1);
	}

	/**
	 * 根据类型获取类型的最后一天
	 * 年为当前年的最后一天,月为当前月最后一天,日为当前日
	 * @param dateStr
	 * @param type
	 * @return
	 * @throws ParseException
	 */
	public static Date getLastDateByType(String dateStr,int type) throws ParseException {
		String parsePattern = getDefaultParsePattern(type);
		Date date = DateUtils.stringToDate(dateStr,parsePattern);
		Date result = null;
		//年需要获取当前年的第一天
		if (type == 1) {
			result = getCurrYearLast(date);
		}
		if (type == 2) {
			result = getMonthLastDay(date);
		}
		if(type == 3) {
			result =  date;
		}
		if (result == null) {
			throw new GlobalException(ResultCode.ILLEAGAL_STRING,"不支持的结束时间计算类型");
		}
		return result;
	}

	public static Date getFirstDateByType(String dateStr,int type) throws ParseException{
		String parsePattern = getDefaultParsePattern(type);
		Date date = DateUtils.stringToDate(dateStr,parsePattern);
		Date result = null;
		//年需要获取当前年的第一天
		if (type == 1) {
			result = getCurrYearFirst(date);
		}
		if (type == 2) {
			result = getMonthFirstDay(date);
		}
		if(type == 3) {
			return date;
		}
		if (result == null) {
			throw new GlobalException(ResultCode.ILLEAGAL_STRING,"不支持的开始时间计算类型");
		}
		return result;
	}

	/**
	 * 日期范围查询,结束日期的处理
	 * 将日期置为第二天的0点
	 * @param startDate
	 * @param parsePattern
	 * @return
	 * @throws ParseException
	 */
	public static Date convertQueryEndDate(String startDate,String parsePattern) throws ParseException{
		Date date = stringToDate(startDate,parsePattern);
		Date nextDay = addDays(date,1);
		return dateTruncForType(nextDay,1);
	}
	public static Date stringToDate(String strTime,String parsePattern) throws ParseException {
		SimpleDateFormat formatter = new SimpleDateFormat(parsePattern);
		Date date = null;
		date = formatter.parse(strTime);
		return date;
	}
	/**
	 *截取到指定类型的日期,从时开始,到秒为止
	 * 如:2018-02-03 12:20:20 typ为1会返回2018-02-03
	 * @param date
	 * @param type
	 * @return
	 */
	public static Date dateTruncForType(Date date,int type){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		switch (type){
			//毫秒
			case 4:
				calendar.set(Calendar.MILLISECOND, 0);
				break;
			//秒
			case 3:
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0);
				break;
			//分
			case 2:
				calendar.set(Calendar.MINUTE, 0);
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0);
				break;
			//时
			case 1:
				calendar.set(Calendar.HOUR_OF_DAY, 0);
				calendar.set(Calendar.MINUTE, 0);
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0);
				break;
			default:
		}
		return calendar.getTime();
	}


	public static String getCurrectTime() {
		SimpleDateFormat formatter = new SimpleDateFormat(FORMATSTRING);
		Date d = new Date();
		return formatter.format(d);
	}

	public static String getTimeByDate(Date d) {
		SimpleDateFormat formatter = new SimpleDateFormat(FORMATSTRING);
		return formatter.format(d);
	}

	public static String getTimeByDate(Date d,String parsePattern) {
		SimpleDateFormat formatter = new SimpleDateFormat(parsePattern);
		return formatter.format(d);
	}

	/**
	 * 13位时间戳转换为date
	 * @param timestamp
	 * @return
	 */
	public static Date getDate(Long timestamp){
		return new Date(timestamp);
	}

	public static long getCurrentTimeForIntFormat(){
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		Date d = new Date();
		return Long.valueOf(formatter.format(d));
	}
	public static Date sqlTimestampToDate(Timestamp timestamp){
		if(timestamp == null){
			return null;
		}
		Date date = new Date(timestamp.getTime());
		return date;
	}

	public static Date addDays(Date date, int amount) {
		return org.apache.commons.lang3.time.DateUtils.addDays(date,amount);
	}

	public static int daysBetween(String begindate, String enddate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(begindate));
		long time1 = cal.getTimeInMillis();
		cal.setTime(sdf.parse(enddate));
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);
		int days = Integer.parseInt(String.valueOf(between_days));
		return days > 0 ? days : 0;
	}

	public static String getDate(String date) {
		return date.substring(0, 10);
	}

	public static String getDateAfter(String date, int days) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMATSTRING);
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(date));
		cal.add(Calendar.DATE, days);
		SimpleDateFormat formatter = new SimpleDateFormat(FORMATSTRING);
		return formatter.format(cal.getTime());

	}

	public static Date getDateAfter(Date date, int days) throws ParseException {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, days);
		return cal.getTime();

	}

	public static String getDateBefore(int ts,int calType) {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMATSTRING);
		Calendar cal = Calendar.getInstance();
		cal.add(calType, -ts);
		SimpleDateFormat formatter = new SimpleDateFormat(FORMATSTRING);
		return formatter.format(cal.getTime());

	}

	public static String getDateAfter(int ts,int calType) {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMATSTRING);
		Calendar cal = Calendar.getInstance();
		cal.add(calType, ts);
		SimpleDateFormat formatter = new SimpleDateFormat(FORMATSTRING);
		return formatter.format(cal.getTime());

	}

	public static boolean after(String date) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMATSTRING);
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(date));
		Calendar today = Calendar.getInstance();
		return cal.after(today);
	}

	public static boolean before(String date) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMATSTRING);
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(date));
		Calendar today = Calendar.getInstance();
		return cal.before(today);
	}

	public static boolean isValidDate(String dataString) {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMATSTRING);
		try {
			sdf.parse(dataString);
		} catch (ParseException e) {
			return false;
		}
		return true;
	}

	public static boolean isPreDay(String date) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(FORMATSTRING);
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(date));
		Calendar todayCal=Calendar.getInstance();
		Date today = new Date();
		today.setHours(0);
		today.setMinutes(0);
		today.setSeconds(0);
		todayCal.setTime(today);
		return cal.before(todayCal);
	}

	/**
	 * 获取当前月第一天
	 * @param date
	 * @return
	 */
	public static Date getMonthFirstDay(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH,1);
		calendar.add(Calendar.MONTH,0);
		return calendar.getTime();
	}

	/**
	 * 获取当前月最后一天
	 * @param date
	 * @return
	 */
	public static Date getMonthLastDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, 0);
		calendar.add(Calendar.MONTH, 1);
		return calendar.getTime();
	}

	/**
	 * 获取当年的最后一天
	 * @param date
	 * @return
	 */
	public static Date getCurrYearLast(Date date){
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(date);
		int currentYear = calendar.get(Calendar.YEAR);
		return getYearLast(currentYear);
	}

	/**
	 * 获取当前年的最后一天
	 * @param date
	 * @return
	 */
	public static Date getCurrYearFirst(Date date){
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(date);
		int currentYear = calendar.get(Calendar.YEAR);
		return getYearFirst(currentYear);
	}

	/**
	 * 获取某年第一天日期
	 * @param year 年份
	 * @return Date
	 */
	public static Date getYearFirst(int year){
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		Date currYearFirst = calendar.getTime();
		return currYearFirst;
	}
	/**
	 * 获取某年最后一天日期
	 * @param year 年份
	 * @return Date
	 */
	public static Date getYearLast(int year){
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		calendar.roll(Calendar.DAY_OF_YEAR, -1);
		Date currYearLast = calendar.getTime();

		return currYearLast;
	}
	/**
	 * 获取默认时期格式化字符串
	 * type为时间所到精度
	 * @param type 1年 2月 3日 4时 5分 6秒
	 * @return
	 */
	public static String getDefaultParsePattern(int type){
		String parsePattern = "";
		switch (type) {
			case 1:
				parsePattern = "yyyy";
				break;
			case 2:
				parsePattern = "yyyy-MM";
				break;
			case 3:
				parsePattern = "yyyy-MM-dd";
				break;
			case 5:
				parsePattern = "yyyy-MM-dd HH";
				break;
			case 6:
				parsePattern = "yyyy-MM-dd HH:ss";
				break;
			case 7:
				parsePattern = "yyyy-MM-dd HH:ss:mm";
				break;
			default:
				throw new GlobalException(ResultCode.ILLEAGAL_STRING,"不支持的时间转换");
		}
		return parsePattern;
	}

	public static void main(String[] args) throws ParseException {
		String dates = "2020";
		Date date = convertQueryStartDate(dates,1);
		System.out.println(DateUtils.getTimeByDate(date,"yyyy-MM-dd"));


	}
}

2、文件相关

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


@Slf4j
public class FileUtil {
    /**
     * 获取文件byte
     * @param file
     * @return
     */
    public static byte[] getIFileStream(File file) {
        byte[] buffer;
        FileInputStream fis = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            bos.close();
            buffer = bos.toByteArray();
            if(file.exists()) {
                file.delete();
            }
        } catch (FileNotFoundException e) {
            throw new GlobalException(e);
        }catch (IOException e) {
            throw new GlobalException(e);
        } finally {
            if(fis !=null){
                try {
                    fis.close();
                } catch (IOException e) {
                   log.error("fis关闭流错误{}",e);
                }
            }
        }
        return buffer;
    }

    /**
     * 获取网络图片进行Base64编码
     *
     * @param url 网络图片路径
     * @return base64 编码g
     * @throws Exception
     */
    public static String getFileBase64(String url) {
        if (url == null || "".equals(url.trim())) {
            return null;
        }
        InputStream inStream = null;
        try {
            URL u = new URL(url);
            // 打开图片路径
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            // 设置请求方式为GET
            conn.setRequestMethod("GET");
            // 设置超时响应时间为5秒
            conn.setConnectTimeout(5000);
            // 通过输入流获取图片数据
            inStream = conn.getInputStream();
            // 读取图片字节数组
            byte[] bytes = IOUtils.toByteArray(inStream);
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            // 返回Base64编码过的字节数组字符串
            return encoder.encode(bytes);
        } catch (Exception e) {
            throw new GlobalException(e);
        }finally {
            if(inStream !=null){
                try {
                    inStream.close();
                } catch (IOException e) {
                    log.error("inStream关闭流错误{}",e);
                }
            }
        }
    }

    /**
     * 二进制流转换为base64
     * @param bytes
     * @return
     */
    public static String getFileBase64(byte[] bytes) {
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(bytes);

    }

    /**
     * 文件流strBase64数组转 InputStream
     * @param strBase64 文件流strBase64数组
     * @return
     */
    public static InputStream base64InputStream(String strBase64) {
        String string = strBase64;
        try {
            // 解码,然后将字节转换为文件,将字符串转换为byte数组
            byte[] bytes = new BASE64Decoder().decodeBuffer(string);
            return new ByteArrayInputStream(bytes);
        } catch (IOException ioe) {
            throw new GlobalException(ioe);
        }
    }

    public static byte[] base64Byte(String strBase64) {
        try {
            byte[] bytes = new BASE64Decoder().decodeBuffer(strBase64);
            return bytes;
        } catch (IOException ioe) {
            throw new GlobalException(ioe);
        }
    }

}

 

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页