在開發的過程當中,一些經常用到的函數可以自己保存起來,下次需要使用的時候可以復制粘貼,這樣可以大大提高效率。下面博主介紹自己的的幾個工具類:時間函數庫、文件處理函數庫、對象的復制
下面附上代碼說明:
###(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);
}
}
}
}
}
}
~~~
- 前言
- Java生成中間logo的二維碼(還可以加上二維碼名稱哦)
- Java我的高效編程之常用函數
- AES加密解密&&SHA1、SHA加密&&MD5加密
- Java中synchronized的使用實例
- Java基礎之集合
- Java基礎之泛型
- Java基礎之枚舉妙用
- 那些年用過的一些前端框架
- 關于正則,那些年一直存在的疑惑解答(正則菜鳥不容錯過)
- 給pdf文件添加防偽水印logo(附工程源碼下載)
- SpringMVC+BUI實現文件上傳(附詳解,源碼下載)
- Java異常封裝(自己定義錯誤碼和描述,附源碼)
- javaweb異常提示信息統一處理(使用springmvc,附源碼)
- 關于Java,那些我心存疑惑的事(不斷更新中...)
- 深入Java虛擬機(1)——Java體系結構
- 深入Java虛擬機(2)——Java的平臺無關性
- 深入Java虛擬機(3)——安全
- 深入Java虛擬機(4)——網絡移動性
- Linux文件編輯命令詳細整理
- 阿里云服務器云數據庫免費體驗(Java Web詳細實例)
- 項目部署、配置、查錯常用到的Linux命令
- Shell腳本了解
- Ajax原理學習
- linux下安裝apache(httpd-2.4.3版本)各種坑
- JSP九大內置對象
- Servlet再度學習
- 開發人員系統功能設計常用辦公軟件分享
- java.lang.ClassNotFoundException:org.springframework.web.context.ContextLoaderListener問題解決
- tomcat內存溢出解決,java.lang.OutOfMemoryError: PermGen space
- 《Java多線程編程核心技術》推薦
- 關于跳槽,是我心浮氣躁?還是我確實該離開了?
- Java I/O學習(附實例和詳解)
- Java經典設計模式之五大創建型模式(附實例和詳解)
- Java經典設計模式之七大結構型模式(附實例和詳解)
- Java經典設計模式之十一種行為型模式(附實例和詳解)
- Java內存管理
- SQL實例整理
- 數據庫面試常問的一些基本概念