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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 面试官问我redis数据类型,我回答了8种

    面试官问我redis数据类型,我回答了8种

    2020年11月20日
  • apache 虚拟主机如何配置[通俗易懂]

    apache 虚拟主机如何配置[通俗易懂]apache虚拟主机如何配置?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。apache虚拟主机就是在apache服务器上配置多个虚拟主机,从而让一个服务器提供多站点的服务实现。通俗来说,就是对同一个服务器上的不同目录进行访问。Apache基于名字的虚拟主机设置这种方式,各个虚拟主机共享同一份Apache,因此有CGI程序运行时,安全性也不高。设置这种虚拟主机时,只要为每一个虚拟主机设置类似如下的信息即可,NameV…

    2022年9月2日
  • 手机丅f丅lcd什么屏_手机丅f丅lcd什么屏_全球首款屏下相机,90Hz OLED屏+4220mAh「建议收藏」

    手机丅f丅lcd什么屏_手机丅f丅lcd什么屏_全球首款屏下相机,90Hz OLED屏+4220mAh「建议收藏」在传统非全面屏手机时,指纹很好实现,放个传感器在屏幕下方区域就行了,但是全面屏时代,很多手机将指纹改为后置或者侧边指纹,不过后置太难看了,侧边指纹体验不是很好,还是屏幕指纹体验最好,OLED非常轻薄,而且具有一定的光通透性,因此可以实现屏幕指纹,指纹是解决了,但是前置摄像头的放置又是一个问题,刘海屏、水滴屏和挖孔屏都不能形成完美的真全面屏。不过功夫不负有心人,任何再难的技术,只要敢想就能实现,敢做…

    2022年8月10日
  • mybatis逆向生成java代码_mybatis生成

    mybatis逆向生成java代码_mybatis生成前言有时候,我们创建实体类需要跟数据库表里面的字段对应起来。假如一张表有数百个字段,那么手动去写实体类的话就比较麻烦,而且容易出错。解决方案其实解决这个问题的方式有很多,本文介绍其中一种解决方案,通过mybatis的逆向工程生成实体类。本文使用的数据库是Oracle,MySQL只需要修改jar包以及generator.properties配置即可。可以从公众号【程序员高手之路】回复“逆向工程”获取源码!Step1修改p…

    2022年8月21日
  • 微信小程序如何连接mysql数据库_微信小程序数据库设计

    微信小程序如何连接mysql数据库_微信小程序数据库设计刚开始学习小程序,做毕业设计,不过一直都被一个问题困扰,就是连接数据库实现数据的同步。通过其他几篇文章总结出来的成果,记录分享一下,欢迎批评指正!1.定义好数据库连接文件名connect.php在activity.php文件调用定义好的数据库连接其返回值是一个包含结果集中所有数据的二维数组。小程序的index.js这里可以在wx.request方法里面通过data进行传参,把不…

    2022年9月17日
  • java用那个软件编,java编译软件 编写java程序用什么软件?[通俗易懂]

    java用那个软件编,java编译软件 编写java程序用什么软件?[通俗易懂]其实装了JDK就可以做JAVA程序了,但要用文本编辑器之类的东西写程序的源代码,用JDK进行调试运行。适合初学者。当有了一定的经验以后你可以选择集成的JAVA编译器,如JCreator,eclipse。JCreator也适合初学者,因为靠近底层。现在企业开发软件最多用的就是eclipse,因为他是开源的,而且本身就是用JAVA编写的,所以兼容性更好。java用什么编译软件用JCreator或ecl…

    2022年6月13日

发表回复

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

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