util java_Java开发常用Util工具类

MyStringUtil、MyCastUtil、MyCollectionUtil、MyArrayUtil、MyPropsUtil

一、字符串工具类MyStringUtil

java内部提供了一个实用工具类-------> StringUtils 不做详细表述

这里MyStringUtil

/**

* StringUtil

* @description: 字符串工具类

**/

public classMyStringUtil {

/**

* 判断是否为空字符串最优代码

* @param str

* @return 如果为空,则返回true

*/

public static booleanisEmpty(String str){

return str == null || str.trim().length() == 0;

}

/**

* 判断字符串是否非空

* @param str 如果不为空,则返回true

* @return

*/

public static booleanisNotEmpty(String str){

return !isEmpty(str);

}

}

二、数据类型转换类MyCastUtil

MyCastUtil

/**

* MyCastUtil

* @description: 数据转型工具类

**/

public classMyCastUtil{

/**

* @Description: 转为String类型

* @Param: [obj]

* @return: java.lang.String 如果参数为null则转为空字符串

*/

public staticString castString(Object obj){

return MyCastUtil.castString(obj,"");

}

/**

* @Description: 转为String类型(提供默认值)

* @Param: [obj, defaultValue] 将obj转为string,如果obj为null则返回default

* @return: String

*/

public staticString castString(Object obj,String defaultValue){

return obj!=null?String.valueOf(obj):defaultValue;

}

/**

* @Description: 转为double类型,如果为null或者空字符串或者格式不对则返回0

* @Param: [obj]

* @return: String

*/

public static doublecastDouble(Object obj){

return MyCastUtil.castDouble(obj,0);

}

/**

* @Description: 转为double类型 ,如果obj为null或者空字符串或者格式不对则返回defaultValue

* @Param: [obj, defaultValue]

* @return: String obj为null或者空字符串或者格式不对返回defaultValue

*/

public static double castDouble(Object obj,doubledefaultValue){

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

}

}

}

returnvalue;

}

/**

* 转为long型,如果obj为null或者空字符串或者格式不对则返回0

* @param obj

* @return

*/

public static longcastLong(Object obj){

return MyCastUtil.castLong(obj,0);

}

/**

* 转为long型(提供默认数值),如果obj为null或者空字符串或者格式不对则返回defaultValue

* @param obj

* @param defaultValue

* @return obj为null或者空字符串或者格式不对返回defaultValue

*/

public static long castLong(Object obj,longdefaultValue){

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

}

}

}

returnvalue;

}

/**

* 转为int型

* @param obj

* @return 如果obj为null或者空字符串或者格式不对则返回0

*/

public static intcastInt(Object obj){

return MyCastUtil.castInt(obj,0);

}

/**

* 转为int型(提供默认值)

* @param obj

* @param defaultValue

* @return 如果obj为null或者空字符串或者格式不对则返回defaultValue

*/

public static int castInt(Object obj,intdefaultValue){

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

}

}

}

returnvalue;

}

/**

* 转为boolean型,不是true的返回为false

* @param obj

* @return

*/

public static booleancastBoolean(Object obj){

return MyCastUtil.castBoolean(obj,false);

}

/**

* 转为boolean型(提供默认值)

* @param obj

* @param defaultValue

* @return

*/

public static boolean castBoolean(Object obj,booleandefaultValue){

boolean value =defaultValue;

if (obj!=null){ //为null则返回默认值

value = Boolean.parseBoolean(castString(obj)); //底层会把字符串和true对比,所以不用判断是否为空字符串

}

returnvalue;

}

}

三、集合工具类MyCollectionUtil

MyCollectionUtil

importorg.apache.commons.collections4.CollectionUtils;

importorg.apache.commons.collections4.MapUtils;

importjava.util.Collection;

importjava.util.Map;

/**

* CollectionUtil

* @description: 集合工具类

**/

public classMyCollectionUtil {

/**

* 判断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);

}

}

四、数组工具类MyArrayUtil

MyArrayUtil

/**

* 数组工具类

*/

public classMyArrayUtil{

/**

* 判断数组是否为空

* @param array

* @return

*/

public static booleanisNotEmpty(Object[] array){

return !isEmpty(array);

}

/**

* 判断数组是否非空

* @param array

* @return

*/

public static booleanisEmpty(Object[] array){

return array==null||array.length==0;

}

}

五、Properties文件操作类

importorg.slf4j.Logger;

importorg.slf4j.LoggerFactory;

importjava.io.FileNotFoundException;

importjava.io.IOException;

importjava.io.InputStream;

importjava.util.Properties;

/**

* 属性文件工具类

*/

public classPropsUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(PropsUtil.class);

/**

* 加载属性文件

* @param fileName fileName一定要在class下面及java根目录或者resource跟目录下

* @return

*/

public staticProperties loadProps(String fileName){

Properties props = newProperties();

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);

}

}

}

returnprops;

}

/**

* 获取字符型属性(默认值为空字符串)

* @param props

* @param key

* @return

*/

public staticString getString(Properties props,String key){

return getString(props,key,"");

}

/**

* 获取字符型属性(可制定默认值)

* @param props

* @param key

* @param defaultValue 当文件中无此key对应的则返回defaultValue

* @return

*/

public staticString getString(Properties props,String key,String defaultValue){

String value =defaultValue;

if(props.containsKey(key)){

value =props.getProperty(key);

}

returnvalue;

}

/**

* 获取数值型属性(默认值为0)

* @param props

* @param key

* @return

*/

public static intgetInt(Properties props,String key){

return getInt(props,key,0);

}

/**

* 获取数值型属性(可指定默认值)

* @param props

* @param key

* @param defaultValue

* @return

*/

public static int getInt(Properties props,String key,intdefaultValue){

int value =defaultValue;

if(props.containsKey(key)){

value =CastUtil.castInt(props.getProperty(key));

}

returnvalue;

}

/**

* 获取布尔型属性(默认值为false)

* @param props

* @param key

* @return

*/

public static booleangetBoolean(Properties props,String key){

return getBoolean(props,key,false);

}

/**

* 获取布尔型属性(可指定默认值)

* @param props

* @param key

* @param defaultValue

* @return

*/

public static booleangetBoolean(Properties props,String key,Boolean defaultValue){

boolean value =defaultValue;

if(props.containsKey(key)){

value =CastUtil.castBoolean(props.getProperty(key));

}

returnvalue;

}

}

org.slf4j

slf4j-log4j12

1.7.9

六、常用流操作工具类

public classStreamUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(StreamUtil.class);

/**

* 从输入流中获取字符串

* @param is

* @return

*/

public staticString getString(InputStream is){

StringBuilder sb = newStringBuilder();

try{

BufferedReader reader = new BufferedReader(newInputStreamReader(is));

String line;

while((line=reader.readLine())!=null){

sb.append(line);

}

} catch(IOException e) {

LOGGER.error("get string failure",e);

throw newRuntimeException(e);

}

returnsb.toString();

}

}

七、编码工具类

public classCodecUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(CodecUtil.class);

/**

* 将URL编码

*/

public staticString encodeURL(String source){

String target;

try{

target = URLEncoder.encode(source,"utf-8");

} catch(UnsupportedEncodingException e) {

LOGGER.error("encode url failure",e);

throw newRuntimeException(e);

//e.printStackTrace();

}

returntarget;

}

/**

* 将URL解码

*/

public staticString dencodeURL(String source){

String target;

try{

target = URLDecoder.decode(source,"utf-8");

} catch(UnsupportedEncodingException e) {

LOGGER.error("encode url failure",e);

throw newRuntimeException(e);

//e.printStackTrace();

}

returntarget;

}

}

八、下载文件工具类

/**

* 下载url的文件到指定文件路径里面,如果文件父文件夹不存在则自动创建

* url 下载的http地址

* path 文件存储地址

* return 如果文件大小大于2k则返回true

*/

public static booleandownloadCreateDir(String url,String path){

HttpURLConnection connection=null;

InputStream in = null;

FileOutputStream o=null;

try{

URL httpUrl=newURL(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=newFile(path);

File parentDir =f.getParentFile();

if (!parentDir.exists()) {

parentDir.mkdirs();

}

if(connection.getResponseCode() == 200){

in =connection.getInputStream();

o=newFileOutputStream(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;

}

九、文件编码转码

将GBK编码的文件转为UTF-8编码的文件

经常配合上一个使用,下载的压缩包解压为文件然后解码。

/**

* 把GBK文件转为UTF-8

* 两个参数值可以为同一个路径

* @param srcFileName 源文件

* @param destFileName 目标文件

* @throws IOException

*/

private static void transferFile(String srcFileName, String destFileName) throwsIOException {

String line_separator = System.getProperty("line.separator");

FileInputStream fis = newFileInputStream(srcFileName);

StringBuffer content = newStringBuffer();

DataInputStream in = newDataInputStream(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();

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值