Java我的高效编程之常用函数

Java我的高效编程之常用函数

在开发的过程当中,一些经常用到的函数可以自己保存起来,下次需要使用的时候可以复制粘贴,这样可以大大提高效率。下面博主介绍自己的的几个工具类:时间函数库、文件处理函数库、对象的复制

下面附上代码说明:

(1)时间函数库

package com.luo.util;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class LuoDateUtils {
   
    /** * @author:罗国辉 * @date: 2015年12月15日 上午9:22:47 * @description:获取现在时间 * @parameter: **/
    public static Date getNow() {
       Date currentTime = new Date();
       return currentTime;
    }

    /** * @author:罗国辉 * @date: 2015年12月15日 上午9:22:47 * @description: 获取现在日期时间 * @parameter: * @return: 返回字符串格式 yyyy-MM-dd HH:mm:ss **/
    public static String getNowDateTimeStr() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTimeString = formatter.format(currentTime);
        return dateTimeString;
    }

    /** * @author:罗国辉 * @date: 2015年12月15日 上午9:22:47 * @description: 获取现在时间 日期 * @parameter: * @return: 返回字符串格式yyyyMMdd HHmmss **/
    public static String getNowDateTimeStrFormatTwo() {
       Date currentTime = new Date();
       SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
       String dateString = formatter.format(currentTime);
       return dateString;
    }

    /** * @author:罗国辉 * @date: 2015年12月15日 上午9:22:47 * @description: 获取现在时间 日期 * @parameter: * @return: 返回字符串格式 yyyy-MM-dd **/
    public static String getNowDateStr() {        
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /** * @author:罗国辉 * @date: 2015年12月15日 上午9:22:47 * @description: 获取现在时间 * @parameter: * @return: 返回字符串格式 HH:mm:ss **/
    public static String getTimeStr() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date currentTime = new Date();
        String timeString = formatter.format(currentTime);
        return timeString;
    }

    /** * @author:罗国辉 * @date: 2015年12月15日 上午9:22:47 * @description:日期时间字符串转日期时间格式 * @parameter: * @return: 返回日期时间格式 **/
    public static Date strToDateTime(String strDateTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDateTime, pos);
        return strtodate;
    }

    /** * @author:罗国辉 * @date: 2015年12月15日 上午9:22:47 * @description:日期字符串转日期格式 * @parameter: * @return: 返回日期格式 **/
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /** * @author:罗国辉 * @date: 2015年12月15日 上午9:22:47 * @description:两个日期时间是否在跨度之内 * @parameter: gapType 跨度类型,如Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_YEAR * @parameter: maxGap 最大跨度值 * @return: 返回日期格式 **/
    public static boolean isWithInDateGap(String startDate, String endDate,  
            int gapType, int maxGap){  
        Date startDateTime = null;  
        Date endDateTime = null;  
        startDateTime = strToDateTime(startDate);  
        endDateTime = strToDateTime(endDate);  
        return isWithInDateGap(startDateTime,endDateTime, gapType, maxGap);  
    }

    public static boolean isWithInDateGap(Date startDate, Date endDate,  
                int gapType, int maxGap) {  
        if (startDate == null) {  
            throw new IllegalArgumentException("The startDate must not be null");  
        }  
        if (endDate == null) {  
            throw new IllegalArgumentException("The endDate must not be null");  
        }  
        if (gapType != Calendar.YEAR && gapType != Calendar.MONTH  
                && gapType != Calendar.DAY_OF_YEAR) {  
            throw new IllegalArgumentException(  
                    "The value of gapType is invalid");  
        }  

        Calendar start = Calendar.getInstance();  
        start.setTime(startDate);  
        start.add(gapType, maxGap);  
        int compare = start.getTime().compareTo(endDate);  
        return compare >= 0;  
    }  

    public static void main(String[] args){
        System.out.println(getNow());
        System.out.println(getNowDateTimeStr());
        System.out.println(getNowDateTimeStrFormatTwo());
        System.out.println(getNowDateStr());
        System.out.println(getTimeStr());
        System.out.println(strToDateTime(getNowDateTimeStr()));
        System.out.println(strToDate(getNowDateStr()));
        System.out.println(isWithInDateGap(getNowDateTimeStr(),getNowDateTimeStr()
        ,Calendar.YEAR,1));
    }
}

(2)文件处理函数库

package com.luo.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LuoFileUtils {
   
    /** * 下载文件 * @throws FileNotFoundException */
    public static void downFile(HttpServletRequest request, 
        HttpServletResponse response,String fileName) throws FileNotFoundException{
        String filePath = request.getSession().getServletContext().getRealPath("/") 
                          + "template/" +  fileName;  //需要下载的文件路径
        // 读到流中
        InputStream inStream = new FileInputStream(filePath);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
            response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }

    /** * @author:罗国辉 * @date: 2015年12月15日 上午10:12:21 * @description: 创建文件目录,若路径存在,就不生成 * @parameter: * @return: **/
    public static void createDocDir(String dirName) {  
        File file = new File(dirName);  
        if (!file.exists()) {  
            file.mkdirs();  
        }  
    }  

    /** * @author:罗国辉 * @date: 2015年12月15日 上午10:12:21 * @description: 本地,在指定路径生成文件。若文件存在,则删除后重建。 * @parameter: * @return: **/
    public static void isExistsMkDir(String dirName){  
        File file = new File(dirName);  
        if (!file.exists()) {  
            file.mkdirs();  
        }  
    } 

    /** * @author:罗国辉 * @date: 2015年12月15日 上午10:15:14 * @description: 创建新文件,若文件存在则删除再创建,若不存在则直接创建 * @parameter: * @return: **/
    public static void creatFileByName(File file){  
        try {  
            if (file.exists()) {  
                file.delete();  
                //发现同名文件:{},先执行删除,再新建。
            }  
            file.createNewFile();  
            //创建文件
        }  
        catch (IOException e) {  
           //创建文件失败
           throw e;
        }  
    }  
}

(3)对象的复制

使用场景:在我们的实际开发当中,经常会遇到这样的情况,一个对象A有几十个属性,对象B包含了对象A所有的属性(属性名称是一样的),对象B还多出那么几个A没有的属性。但是希望把A对象的属性值全部都set进B里面。如果不断的set,get会显得很繁琐。下面就是对象复制的代码(依赖spring):

package com.luo.util;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;

public abstract class CopyObjectUtils extends org.springframework.beans.BeanUtils {
    public static void copyProperties(Object source, Object target) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        for (PropertyDescriptor targetPd : targetPds) {
            if (targetPd.getWriteMethod() != null) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null && sourcePd.getReadMethod() != null) {
                    try {
                        Method readMethod = sourcePd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object srcValue = readMethod.invoke(source);
                        if(srcValue == null){
                            continue;
                        }
                        Object value=srcValue;
                        //转换Double 与 BigDecimal
                        if(sourcePd.getPropertyType().isAssignableFrom( Double.class) && targetPd.getPropertyType().isAssignableFrom(BigDecimal.class)){
                            value = new BigDecimal((Double)srcValue);
                        }
                        if(sourcePd.getPropertyType().isAssignableFrom( BigDecimal.class) && targetPd.getPropertyType().isAssignableFrom(Double.class)){
                            value = ((BigDecimal)srcValue).doubleValue();
                        }
                        //转换Long 与 BigDecimal
                        if(sourcePd.getPropertyType().isAssignableFrom( Long.class) && targetPd.getPropertyType().isAssignableFrom(BigDecimal.class)){
                            value = new BigDecimal((Long)srcValue);
                        }
                        if(sourcePd.getPropertyType().isAssignableFrom( BigDecimal.class) && targetPd.getPropertyType().isAssignableFrom(Long.class)){
                            value = ((BigDecimal)srcValue).longValue();
                        }
                        //转换String为数字的 与 BigDecimal
                        if(sourcePd.getPropertyType().isAssignableFrom( String.class) && targetPd.getPropertyType().isAssignableFrom(BigDecimal.class)){
                            String srcValueStr = (String)srcValue;
                            if(srcValueStr.matches("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){2})$")){
                                value = new BigDecimal((String)srcValue);
                            }
                        }

                        // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
                        if (value != null) {
                            Method writeMethod = targetPd.getWriteMethod();
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }
                    } catch (Throwable ex) {
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
                }
            }
        }
    }
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/2312.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • C语言xml文件存储数据文件(一)

    C语言xml文件存储数据文件(一)————————————————版权声明:本文为CSDN博主「jack8126」的原创文章,遵循CC4.0BY-SA版权协议,转载请附上原文出处链接及本声明。原文链接:https://blog.csdn.net/jack8126/article/details/117004179本文,摘抄的,未验证过,纯属保存留用,请看原作者。c语言读取xml配置文件c语言要实现读取xml配置文件的功能。需要先编译libxml2库。1、编译libxml2库libxml2库从网络下载得到,这里下载的文件是:

    2022年7月12日
    27
  • nextSibling的兼容问题「建议收藏」

    nextSibling的兼容问题「建议收藏」这个有两个兼容性,innerText不是所有浏览器都兼容的,要用innerHTML 然后就是,对于节点关系,ie有事会将期间的空格当成一个文本节点,但火狐就不会,因此你的nextSibling很可能在ie下取到的是一个文本节点,换在火狐下就是另外一个。本文转自:http://ailantian.bokee.com/6418694.html原文如下:网

    2022年7月13日
    15
  • visual studio code使用教程_visual studio code 权威指南 pdf

    visual studio code使用教程_visual studio code 权威指南 pdfsnippet,也即代码片,指的是能够帮助输入重复代码模式,比如循环或条件语句,的模板。本文即旨于详实地介绍如何在vscode中设置snippet。

    2022年8月21日
    11
  • 字符串常量池有什么用_字符串常量池在堆中还是方法区

    字符串常量池有什么用_字符串常量池在堆中还是方法区看网上的介绍,对于字符串常量池中到底保存的是字符串对象,还是字符串对象的引用,众说纷纭…看jdk1.8对intern()的说明.Whentheinternmethodisinvoked,ifthepoolalreadycontainsastringequaltothisStringobjectasdeterminedbytheequals(…

    2022年7月28日
    4
  • 人人网登录界面[通俗易懂]

    人人网登录界面[通俗易懂]<!DOCTYPEhtml><html> <head><metacharset="UTF-8"><title

    2022年8月2日
    9
  • Arduino学习笔记(12) — MPU6050与卡尔曼滤波算法实践「建议收藏」

    Arduino学习笔记(12) — MPU6050与卡尔曼滤波算法实践「建议收藏」01简介:WhyMPU6050?MPU6050等IMU传感器用于自平衡机器人,无人机,智能手机等。IMU传感器帮助我们在三维空间中获得连接到传感器的物体的位置。这些值通常是角度,以帮助我们确定其位置。它们用于检测智能手机的方向,或者用于Fitbit等可穿戴设备,它使用IMU传感器跟踪运动。MPU6050它是全球首例整合性6轴运动处理组件,俗称的六轴陀螺仪(xyz三轴的倾斜…

    2022年6月21日
    142

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号