Java开发常用Util工具类-StringUtil、CastUtil、CollectionUtil、ArrayUtil、PropsUtil
字符串工具类
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;
- }
下载文件工具类
- /**
- * 下载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[];
- File f=new File(path);
- File parentDir = f.getParentFile();
- if (!parentDir.exists()) {
- parentDir.mkdirs();
- }
- if(connection.getResponseCode() == ){
- in = connection.getInputStream();
- o=new FileOutputStream(path);
- int n=;
- while((n=in.read(data))>){
- o.write(data, , n);
- o.flush();
- }
- }
- if(f.length()>){ //代表文件大小
- 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();
- }
Java开发常用Util工具类-StringUtil、CastUtil、CollectionUtil、ArrayUtil、PropsUtil的更多相关文章
- java中常用的工具类(一)
我们java程序员在开发项目的是常常会用到一些工具类.今天我汇总了一下java中常用的工具方法.大家可以在项目中使用.可以收藏!加入IT江湖官方群:383126909 我们一起成长 一.String工 ...
- java中常用的工具类(二)
下面继续分享java中常用的一些工具类,希望给大家带来帮助! 1.FtpUtil Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
- java中常用的工具类(三)
继续分享java中常用的一些工具类.前两篇的文章中有人评论使用Apache 的lang包和IO包,或者Google的Guava库.后续的我会加上的!谢谢支持IT江湖 一.连接数据库的综合类 ...
- 【在线工具】java开发常用在线工具
转自:常用工具页面 Java源代码搜索 Grepcode是一个面向于Java开发人员的网站,在这里你可以通过Java的projects.classes等各种关键字在线查看它对应的源码,知道对应的pro ...
- Java基础学习(五)-- Java中常用的工具类、枚举、Java中的单例模式之详解
Java中的常用类 1.Math : 位于java.lang包中 (1)Math.PI:返回一个最接近圆周率的 (2)Math.abs(-10):返回一个数的绝对值 (3)Math.cbrt(27): ...
- 【uniapp 开发】字符串工具类 StringUtil
替换字符串中的所有 "***" 子串 var str='Is this all there is'; var subStr=new RegExp('is','ig');//创建正则 ...
- Android开发之常用必备工具类图片bitmap转成字符串string与String字符串转换为bitmap图片格式
作者:程序员小冰,CSDN博客:http://blog.csdn.net/qq_21376985 QQ986945193 博客园主页:http://www.cnblogs.com/mcxiaobing ...
- Java基础学习总结(70)——开发Java项目常用的工具汇总
要想全面了解java开发工具,我们首先需要先了解一下java程序的开发过程,通过这个过程我们能够了解到java开发都需要用到那些工具. 首先我们先了解完整项目开发过程,如图所示: 从上图中我们能看到一 ...
- Java语言Lang包下常用的工具类介绍_java - JAVA
文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 无论你在开发哪中 Java 应用程序,都免不了要写很多工具类/工具函数.你可知道,有很多现成的工具类可用,并且代码质量都 ...
随机推荐
- MyEclipse 相关设置
1. MyElipse复制项目后,修改项目的发布名称的方式.右击你的项目,选择 properties -- > MyElipse -- > web,然后修改名称即可. 2. IDE查看源代 ...
- linux服务器---安装swat
安装swat swat是一个图形化的samba管理软件,可以帮助不熟悉的人去灵活的配置samba服务, 1.安装swat [root@localhost wj]#yum install -y samb ...
- 删除github上个人的repositories的操作步骤
- 怎么说, 开发会很乐意去主动修改bug?
怎么说, 开发会很乐意去主动修改bug? 一图顶上千言万语,如下:
- GitHub Desktop离线安装包
GitHub Desktop离线安装包.上传时间是2017-02-05 版本3.3.4.0,Git shell版本是v2.11.0. 百度网盘的下载链接: http://pan.baidu.com/s ...
- 20145302张薇 《网络对抗技术》 web基础
20145302张薇 <网络对抗> web基础 实验问题回答 1.什么是表单 表单在网页中主要负责数据采集功能:一般网页上需要用户输入.选择的地方都会用到表单 表单标签:即,用于确定表单所 ...
- 20165310 Java实验四 《Android程序设计》
20165310 实验四 <Android程序设计> 第24章:初识Android 任务一:改写res目录中的内容,Hello World后要显示自己的学号,自己学号前后一名同学的学号 首 ...
- Python数据分析入门之pandas基础总结
Pandas--"大熊猫"基础 Series Series: pandas的长枪(数据表中的一列或一行,观测向量,一维数组...) Series1 = pd.Series(np.r ...
- 【第十二章】 springboot + mongodb(复杂查询)
简单查询:使用自定义的XxxRepository接口即可.(见 第十一章 springboot + mongodb(简单查询)) 复杂查询:使用MongoTemplate以及一些查询条件构建类(Bas ...
- [JavaScript] - form表单转json的插件
jquery.serializejson.js 之前好像记录过,做项目又用到了再记下 在页面中引入js后就可以使用了 示例: //点击设置微信信息的form表单提交按钮后,执行wxConfig的con ...