字符串工具類
StringUtil.java
package com.***.util; /** * StringUtil * @description: 字符串工具類 **/ public class StringUtil { /** * 判斷是否為空字符串最優代碼 * @param str * @return 如果為空,則返回true */ public static boolean isEmpty(String str){ return str == null || str.trim().length() == 0; } /** * 判斷字符串是否非空 * @param str 如果不為空,則返回true * @return */ public static boolean isNotEmpty(String str){ return !isEmpty(str); } }
數據類型轉換類
CastUtil.java
package com.***.util; /** * CastUtil * @description: 數據轉型工具類 **/ public class CastUtil { /** * @Description: 轉為String類型 * @Param: [obj] * @return: java.lang.String 如果參數為null則轉為空字符串 */ public static String castString(Object obj){ return CastUtil.castString(obj,""); } /** * @Description: 轉為String類型(提供默認值) * @Param: [obj, defaultValue] 將obj轉為string,如果obj為null則返回default * @return: String */ public static String castString(Object obj,String defaultValue){ return obj!=null?String.valueOf(obj):defaultValue; } /** * @Description: 轉為double類型,如果為null或者空字符串或者格式不對則返回0 * @Param: [obj] * @return: String */ public static double castDouble(Object obj){ return CastUtil.castDouble(obj,0); } /** * @Description: 轉為double類型 ,如果obj為null或者空字符串或者格式不對則返回defaultValue * @Param: [obj, defaultValue] * @return: String obj為null或者空字符串或者格式不對返回defaultValue */ public static double castDouble(Object obj,double defaultValue){ double value = defaultValue; //聲明結果,把默認值賦給結果 if (obj!=null){ //判斷是否為null String strValue = castString(obj); //轉換為String if (StringUtil.isNotEmpty(strValue)){ //判斷字符串是否為空(是否為空只能判斷字符串,不能判斷Object) try{ value = Double.parseDouble(strValue); //不為空則把值賦給value }catch (NumberFormatException e){ value = defaultValue; //格式不對把默認值賦給value } } } return value; } /** * 轉為long型,如果obj為null或者空字符串或者格式不對則返回0 * @param obj * @return */ public static long castLong(Object obj){ return CastUtil.castLong(obj,0); } /** * 轉為long型(提供默認數值),如果obj為null或者空字符串或者格式不對則返回defaultValue * @param obj * @param defaultValue * @return obj為null或者空字符串或者格式不對返回defaultValue */ public static long castLong(Object obj,long defaultValue){ long value = defaultValue; //聲明結果,把默認值賦給結果 if (obj!=null){ //判斷是否為null String strValue = castString(obj); //轉換為String if (StringUtil.isNotEmpty(strValue)){ //判斷字符串是否為空(是否為空只能判斷字符串,不能判斷Object) try{ value = Long.parseLong(strValue); //不為空則把值賦給value }catch (NumberFormatException e){ value = defaultValue; //格式不對把默認值賦給value } } } return value; } /** * 轉為int型 * @param obj * @return 如果obj為null或者空字符串或者格式不對則返回0 */ public static int castInt(Object obj){ return CastUtil.castInt(obj,0); } /** * 轉為int型(提供默認值) * @param obj * @param defaultValue * @return 如果obj為null或者空字符串或者格式不對則返回defaultValue */ public static int castInt(Object obj,int defaultValue){ int value = defaultValue; //聲明結果,把默認值賦給結果 if (obj!=null){ //判斷是否為null String strValue = castString(obj); //轉換為String if (StringUtil.isNotEmpty(strValue)){ //判斷字符串是否為空(是否為空只能判斷字符串,不能判斷Object) try{ value = Integer.parseInt(strValue); //不為空則把值賦給value }catch (NumberFormatException e){ value = defaultValue; //格式不對把默認值賦給value } } } return value; } /** * 轉為boolean型,不是true的返回為false * @param obj * @return */ public static boolean castBoolean(Object obj){ return CastUtil.castBoolean(obj,false); } /** * 轉為boolean型(提供默認值) * @param obj * @param defaultValue * @return */ public static boolean castBoolean(Object obj,boolean defaultValue){ boolean value = defaultValue; if (obj!=null){ //為null則返回默認值 value = Boolean.parseBoolean(castString(obj)); //底層會把字符串和true對比,所以不用判斷是否為空字符串 } return value; } }
集合工具類
CollectionUtil.java
package com.***.util; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import java.util.Collection; import java.util.Map; /** * CollectionUtil * @description: 集合工具類 **/ public class CollectionUtil { /** * 判斷collection是否為空 * @param collection * @return */ public static boolean isEmpty(Collection<?> collection){ //return CollectionUtils.isEmpty(collection); return collection == null || collection.isEmpty(); } /** * 判斷Collection是否非空 * @return */ public static boolean isNotEmpty(Collection<?> collection){ return !isEmpty(collection); } /** * 判斷map是否為空 * @param map * @return */ public static boolean isEmpty(Map<?,?> map){ //return MapUtils.isEmpty(map); return map == null || map.isEmpty(); } /** * 判斷map是否非 * @param map * @return */ public static boolean isNotEmpty(Map<?,?> map){ return !isEmpty(map); } }
數組工具類
ArrayUtil.java
/** * 數組工具類 */ public class ArrayUtil { /** * 判斷數組是否為空 * @param array * @return */ public static boolean isNotEmpty(Object[] array){ return !isEmpty(array); } /** * 判斷數組是否非空 * @param array * @return */ public static boolean isEmpty(Object[] array){ return array==null||array.length==0; } }
Properties文件操作類
PropsUtil.java
package com.***.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * 屬性文件工具類 */ public class PropsUtil { private static final Logger LOGGER = LoggerFactory.getLogger(PropsUtil.class); /** * 加載屬性文件 * @param fileName fileName一定要在class下面及java根目錄或者resource跟目錄下 * @return */ public static Properties loadProps(String fileName){ Properties props = new Properties(); InputStream is = null; try { //將資源文件加載為流 is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
props.load(is); if(is==null){ throw new FileNotFoundException(fileName+"file is not Found"); } } catch (FileNotFoundException e) { LOGGER.error("load properties file filure",e); }finally { if(is !=null){ try { is.close(); } catch (IOException e) { LOGGER.error("close input stream failure",e); } } } return props; } /** * 獲取字符型屬性(默認值為空字符串) * @param props * @param key * @return */ public static String getString(Properties props,String key){ return getString(props,key,""); } /** * 獲取字符型屬性(可制定默認值) * @param props * @param key * @param defaultValue 當文件中無此key對應的則返回defaultValue * @return */ public static String getString(Properties props,String key,String defaultValue){ String value = defaultValue; if (props.containsKey(key)){ value = props.getProperty(key); } return value; } /** * 獲取數值型屬性(默認值為0) * @param props * @param key * @return */ public static int getInt(Properties props,String key){ return getInt(props,key,0); } /** * 獲取數值型屬性(可指定默認值) * @param props * @param key * @param defaultValue * @return */ public static int getInt(Properties props,String key,int defaultValue){ int value = defaultValue; if (props.containsKey(key)){ value = CastUtil.castInt(props.getProperty(key)); } return value; } /** * 獲取布爾型屬性(默認值為false) * @param props * @param key * @return */ public static boolean getBoolean(Properties props,String key){ return getBoolean(props,key,false); } /** * 獲取布爾型屬性(可指定默認值) * @param props * @param key * @param defaultValue * @return */ public static boolean getBoolean(Properties props,String key,Boolean defaultValue){ boolean value = defaultValue; if (props.containsKey(key)){ value = CastUtil.castBoolean(props.getProperty(key)); } return value; } }
用到的maven坐標
<!--slf4j--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.9</version> </dependency>
常用流操作工具類
StreamUtil.java
public class StreamUtil { private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtil.class); /** * 從輸入流中獲取字符串 * @param is * @return */ public static String getString(InputStream is){ StringBuilder sb = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while((line=reader.readLine())!=null){ sb.append(line); } } catch (IOException e) { LOGGER.error("get string failure",e); throw new RuntimeException(e); } return sb.toString(); } }
編碼工具類
public class CodecUtil { private static final Logger LOGGER = LoggerFactory.getLogger(CodecUtil.class); /** * 將URL編碼 */ public static String encodeURL(String source){ String target; try { target = URLEncoder.encode(source,"utf-8"); } catch (UnsupportedEncodingException e) { LOGGER.error("encode url failure",e); throw new RuntimeException(e); //e.printStackTrace(); } return target; } /** * 將URL解碼 */ public static String dencodeURL(String source){ String target; try { target = URLDecoder.decode(source,"utf-8"); } catch (UnsupportedEncodingException e) { LOGGER.error("encode url failure",e); throw new RuntimeException(e); //e.printStackTrace(); } return target; } }
Json工具類
package org.smart4j.framework.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * @program: JsonUtil * @description: JSON工具類 * @author: Created by QiuYu * @create: 2018-10-24 15:55 */ public class JsonUtil { private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class); private static final ObjectMapper OBJECT_MAPPER =new ObjectMapper(); /** * 將POJO轉換為JSON */ public static <T> String toJson(T obj){ String json; try { json = OBJECT_MAPPER.writeValueAsString(obj); } catch (JsonProcessingException e) { LOGGER.error("convert POJO to JSON failure",e); throw new RuntimeException(e); //e.printStackTrace(); } return json; } /** * 將JSON轉為POJO */ public static <T> T fromJson(String json,Class<T> type){ T pojo; try { pojo = OBJECT_MAPPER.readValue(json,type); } catch (IOException e) { LOGGER.error("convert JSON to POJO failure",e); throw new RuntimeException(e); //e.printStackTrace(); } return pojo; } }
日期工具類
DataUtil.java
/** * 根據年月獲取當月最后一天 * @param yearmonth yyyy-MM * @return yyyy-MM-dd * @throws ParseException */ public static String getLastDayOfMonth(String yearmonth) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM"); Date dd = format.parse(yearmonth); Calendar cal = Calendar.getInstance(); cal.setTime(dd); int cc=cal.getActualMaximum(Calendar.DAY_OF_MONTH); String result = yearmonth+"-"+cc; return result; } catch (ParseException e) { e.printStackTrace(); } return null; }
時間戳工具類
/** * 時間戳轉換成日期格式字符串 * @param seconds 精確到秒的字符串 * @param formatStr 為null時默認yyyy-MM-dd HH:mm:ss * @return 返回日期字符串 */ public static String timeStamp2Date(String seconds,String format) { if(seconds == null || seconds.isEmpty() || seconds.equals("null")){ return ""; } if(format == null || format.isEmpty()){ format = "yyyy-MM-dd HH:mm:ss"; } SimpleDateFormat sdf = new SimpleDateFormat(format); //Date是精確到毫秒的13位時間戳,所以秒要*1000 Date date = new Date(Long.valueOf(seconds+"000")); String dateString = sdf.format(date); return dateString; } /** * 日期格式字符串轉換成時間戳 * @param date 字符串日期 * @param format 默認:yyyy-MM-dd HH:mm:ss * @return 精確到秒的時間戳 */ public static String date2TimeStamp(String date_str,String format){ if(format == null || format.isEmpty()){ format = "yyyy-MM-dd HH:mm:ss"; } try { SimpleDateFormat sdf = new SimpleDateFormat(format); return String.valueOf(sdf.parse(date_str).getTime()/1000); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 取得當前時間戳(精確到秒) * @return */ public static String getNowTimeStamp(){ long time = System.currentTimeMillis(); String timestamp = String.valueOf(time/1000); return timestamp; }
精度計算工具類
DoubleTool.java
package com.gmtx.system.tools; import java.io.Serializable; import java.math.BigDecimal; import java.math.RoundingMode; /** * @ClassName: DoubleTool * @Description: java類精確計算小數 * double的計算不精確,會有類似0.0000000000000002的誤差,正確的方法是使用BigDecimal或者用整型,整型地方法適合於貨幣精度已知的情況,比如12.11+1.10轉成1211+110計算,最后再/100即可 * @author 秋雨 * 修改歷史 * 序號------原因------修改人---日期--- * 1. * 2. */ public class DoubleTool implements Serializable { private static final long serialVersionUID = -3345205828566485102L; //默認除法運算精度 private static final Integer DEF_DIV_SCALE = 2; /** * 提供精確的加法運算。 * @param value1 被加數 * @param value2 加數 * @return 兩個參數的和 */ public static Double add(Double value1, Double value2) { BigDecimal b1 = new BigDecimal(Double.toString(value1)); BigDecimal b2 = new BigDecimal(Double.toString(value2)); return b1.add(b2).doubleValue(); } /** * 提供精確的減法運算。 * @param value1 被減數 * @param value2 減數 * @return 兩個參數的差 */ public static double sub(Double value1, Double value2) { BigDecimal b1 = new BigDecimal(Double.toString(value1)); BigDecimal b2 = new BigDecimal(Double.toString(value2)); return b1.subtract(b2).doubleValue(); } /** * 提供精確的乘法運算。 * @param value1 被乘數 * @param value2 乘數 * @return 兩個參數的積 */ public static Double mul(Double value1, Double value2) { BigDecimal b1 = new BigDecimal(Double.toString(value1)); BigDecimal b2 = new BigDecimal(Double.toString(value2)); return b1.multiply(b2).doubleValue(); } /** * 提供(相對)精確的除法運算,當發生除不盡的情況時, 精確到小數點以后10位,以后的數字四舍五入。 * @param dividend 被除數 * @param divisor 除數 * @return 兩個參數的商 */ public static Double divide(Double dividend, Double divisor) { return divide(dividend, divisor, DEF_DIV_SCALE); } /** * 提供(相對)精確的除法運算。 當發生除不盡的情況時,由scale參數指定精度,以后的數字四舍五入。 * @param dividend 被除數 * @param divisor 除數 * @param scale 表示表示需要精確到小數點以后幾位。 * @return 兩個參數的商 */ public static Double divide(Double dividend, Double divisor, Integer scale) { if (scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Double.toString(dividend)); BigDecimal b2 = new BigDecimal(Double.toString(divisor)); return b1.divide(b2, scale,RoundingMode.HALF_UP).doubleValue(); } /** * 提供指定數值的(精確)小數位四舍五入處理。 * @param value 需要四舍五入的數字 * @param scale 小數點后保留幾位 * @return 四舍五入后的結果 */ public static double round(double value,int scale){ if(scale<0){ throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(value)); BigDecimal one = new BigDecimal("1"); return b.divide(one,scale, RoundingMode.HALF_UP).doubleValue(); } }
下載文件工具類
/** * 下載url的文件到指定文件路徑里面,如果文件父文件夾不存在則自動創建 * url 下載的http地址 * path 文件存儲地址 * return 如果文件大小大於2k則返回true */ public static boolean downloadCreateDir(String url,String path){ HttpURLConnection connection=null; InputStream in = null; FileOutputStream o=null; try{ URL httpUrl=new URL(url); connection = (HttpURLConnection) httpUrl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("Charset", "gbk"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestMethod("GET"); byte[] data=new byte[1024]; File f=new File(path); File parentDir = f.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } if(connection.getResponseCode() == 200){ in = connection.getInputStream(); o=new FileOutputStream(path); int n=0; while((n=in.read(data))>0){ o.write(data, 0, n); o.flush(); } } if(f.length()>2048){ //代表文件大小 return true; //如果文件大於2k則返回true } }catch(Exception ex){ ex.printStackTrace(); }finally{ try{ if(in != null){ in.close(); } }catch(IOException ex){ ex.printStackTrace(); } try{o.close();}catch(Exception ex){} try{connection.disconnect();}catch(Exception ex){} } return false; }
解壓ZIP工具類
package com.***.tools; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * 解壓zip文件 */ public final class ZipUtil { private static final int buffer = 2048; /** * 解壓Zip文件 * @param path zip文件目錄 */ public static void unZip(String path) { int count = -1; String savepath = ""; File file = null; InputStream is = null; FileOutputStream fos = null; BufferedOutputStream bos = null; savepath = path.substring(0, path.lastIndexOf(".")) + File.separator; // 保存解壓文件目錄 new File(savepath).mkdir(); // 創建保存目錄 ZipFile zipFile = null; try { zipFile = new ZipFile(path,Charset.forName("GBK")); // 解決中文亂碼問題 Enumeration<?> entries = zipFile.entries(); //枚舉ZIP中的所有文件 while (entries.hasMoreElements()) { byte buf[] = new byte[buffer]; ZipEntry entry = (ZipEntry) entries.nextElement(); String filename = entry.getName(); //獲取文件名 filename = savepath + filename; boolean ismkdir = false; if (filename.lastIndexOf("/") != -1) { // 檢查此文件是否帶有文件夾 ismkdir = true; } if (entry.isDirectory()) { // 如果此枚舉文件是文件夾則創建,並且遍歷下一個 file = new File(filename); file.mkdirs(); continue; } file = new File(filename); //此枚舉文件不是目錄 if (!file.exists()) { //如果文件不存在並且文件帶有目錄 if (ismkdir) { new File(filename.substring(0, filename .lastIndexOf("/"))).mkdirs(); // 先創建目錄 } } file.createNewFile(); //再創建文件 is = zipFile.getInputStream(entry); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos, buffer); while ((count = is.read(buf)) > -1) { bos.write(buf, 0, count); } bos.flush(); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (bos != null) { bos.close(); } if (fos != null) { fos.close(); } if (is != null) { is.close(); } if (zipFile != null) { zipFile.close(); } } catch (Exception e) { e.printStackTrace(); } } } }
文件編碼轉碼
將GBK編碼的文件轉為UTF-8編碼的文件
經常配合上一個使用,下載的壓縮包解壓為文件然后解碼。
/** * 把GBK文件轉為UTF-8 * 兩個參數值可以為同一個路徑 * @param srcFileName 源文件 * @param destFileName 目標文件 * @throws IOException */ private static void transferFile(String srcFileName, String destFileName) throws IOException { String line_separator = System.getProperty("line.separator"); FileInputStream fis = new FileInputStream(srcFileName); StringBuffer content = new StringBuffer(); DataInputStream in = new DataInputStream(fis); BufferedReader d = new BufferedReader(new InputStreamReader(in, "GBK")); //源文件的編碼方式 String line = null; while ((line = d.readLine()) != null) content.append(line + line_separator); d.close(); in.close(); fis.close(); Writer ow = new OutputStreamWriter(new FileOutputStream(destFileName), "utf-8"); //需要轉換的編碼方式 ow.write(content.toString()); ow.close(); }
