apatch 常用工具类以及方法

Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动。下面是我这几年做开发过程中自己用过的工具类做简单介绍。

 

 

组件功能介绍
BeanUtils提供了对于JavaBean进行各种操作,克隆对象,属性等等.
BetwixtXML与Java对象之间相互转换.
Codec处理常用的编码方法的工具类包 例如DES、SHA1、MD5、Base64等.
Collectionsjava集合框架操作.
Compressjava提供文件打包 压缩类库.
Configuration一个java应用程序的配置管理类库.
DBCP提供数据库连接池服务.
DbUtils提供对jdbc 的操作封装来简化数据查询和记录读取操作.
Emailjava发送邮件 对javamail的封装.
FileUpload提供文件上传功能.
HttpClient提供HTTP客户端与服务器的各种通讯操作. 现在已改成HttpComponents
IOio工具的封装.
LangJava基本对象方法的工具类包 如:StringUtils,ArrayUtils等等.
Logging提供的是一个Java 的日志接口.
Validator提供了客户端和服务器端的数据验证框架.

 

由于我转载的地方也是从别人那儿转载过来的,而且没有标明出处,所以这里也无法标明出处

 

 

1. org.apache.commons.io.IOUtils

  • closeQuietly()
  • toString()
  • copy()
  • toByteArray()
  • write()
  • toInputStream()
  • readLines()
  • copyLarge()
  • lineIterator()
  • readFully()

2. org.apache.commons.io.FileUtils

  • deleteDirectory()
  • readFileToString()
  • deleteQuietly()
  • copyFile()
  • writeStringToFile()
  • forceMkdir()
  • write()
  • listFiles()
  • copyDirectory()
  • forceDelete()

3. org.apache.commons.lang.StringUtils

  • isBlank()
  • isNotBlank()
  • isEmpty()
  • isNotEmpty()
  • equals()
  • join()
  • split()
  • EMPTY
  • trimToNull()
  • replace()

4. org.apache.http.util.EntityUtils

  • toString()
  • consume()
  • toByteArray()
  • consumeQuietly()
  • getContentCharSet()

 

5. org.apache.commons.lang3.StringUtils

  • isBlank ( )
  • isNotBlank ( )
  • isEmpty ( )
  • isNotEmpty ( )
  • join ( )
  • equals ( )
  • split ( )
  • EMPTY
  • replace ( )
  • capitalize ( )

6. org.apache.commons.io.FilenameUtils

 

  • getExtension()
  • getBaseName()
  • getName()
  • concat()
  • removeExtension()
  • normalize()
  • wildcardMatch()
  • separatorsToUnix()
  • getFullPath()
  • isExtension()

7. org.springframework.util.StringUtils

 

  • hasText()
  • hasLength()
  • isEmpty()
  • commaDelimitedListToStringArray()
  • collectionToDelimitedString()
  • replace()
  • delimitedListToStringArray()
  • uncapitalize()
  • collectionToCommaDelimitedString()
  • tokenizeToStringArray()

8. org.apache.commons.lang.ArrayUtils

  • contains()
  • addAll()
  • clone()
  • isEmpty()
  • add()
  • EMPTY_BYTE_ARRAY
  • subarray()
  • indexOf()
  • isEquals()
  • toObject()

9. org.apache.commons.lang.StringEscapeUtils

  • escapeHtml()
  • unescapeHtml()
  • escapeXml()
  • escapeSql()
  • unescapeJava()
  • escapeJava()
  • escapeJavaScript()
  • unescapeXml()
  • unescapeJavaScript()

10. org.apache.http.client.utils.URLEncodedUtils

  • format()
  • parse()

11. org.apache.commons.codec.digest.DigestUtils

  • md5Hex()
  • shaHex()
  • sha256Hex()
  • sha1Hex()
  • sha()
  • md5()
  • sha512Hex()
  • sha1()

12. org.apache.commons.collections.CollectionUtils

  • isEmpty()
  • isNotEmpty()
  • select()
  • transform()
  • filter()
  • find()
  • collect()
  • forAllDo()
  • addAll()
  • isEqualCollection()

13. org.apache.commons.lang3.ArrayUtils

  • contains()
  • isEmpty()
  • isNotEmpty()
  • add()
  • clone()
  • addAll()
  • subarray()
  • indexOf()
  • EMPTY_OBJECT_ARRAY
  • EMPTY_STRING_ARRAY

14. org.apache.commons.beanutils.PropertyUtils

  • getProperty()
  • setProperty()
  • getPropertyDescriptors()
  • isReadable()
  • copyProperties()
  • getPropertyDescriptor()
  • getSimpleProperty()
  • isWriteable()
  • setSimpleProperty()
  • getPropertyType()

15. org.apache.commons.lang3.StringEscapeUtils

  • unescapeHtml4()
  • escapeHtml4()
  • escapeXml()
  • unescapeXml()
  • escapeJava()
  • escapeEcmaScript()
  • unescapeJava()
  • escapeJson()
  • escapeXml10()

16. org.apache.commons.beanutils.BeanUtils

  • copyProperties()
  • getProperty()
  • setProperty()
  • describe()
  • populate()
  • copyProperty()
  • cloneBean()

 

 

 

添加依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>
<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.1</version>
</dependency>
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.3</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.3.6.RELEASE</version>
</dependency>

 

  17 - 字符串处理

import org.apache.commons.lang3.StringUtils;

boolean StringUtils.isBlank(str);            // " " 为 true
boolean StringUtils.isEmpty(str);            // " " 为 false
boolean StringUtils.isNotBlank(str);
boolean StringUtils.isNotEmpty(str);

String[] StringUtils.split(str,char/String,max);//切割字符串,使用给定字符 ;  max 主要是用来处理空内容的

String StringUtils.capitalize(str);            //首字母大写
String StringUtils.uncapitalize(str);        //首字母小写

boolean StringUtils.isNumeric(str);
boolean StringUtils.isNumericSpace(str);    // "" 为true "12 3" 为 true

String StringUtils.join(array/Iterable,chat/String);    // 类似于 js 的 join ,使用给定字符拼接数组或集合中的元素

String StringUtils.leftPad(str,size,padChar);        //给左边拼接固定长度的字符
String StringUtils.rightPad(str,size,padChar);        //右边拼接固定长度的字符



18- 格式化信息

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

DateFormatUtils.format(Date/Calendar/long,pattern);
DateFormatUtils.ISO_DATE_FORMAT.format(Date/Calendar/long);        // yyyy-MM-dd
DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(Date/Calendar/long);// HH:mm:ss

DurationFormatUtils.formatDuration(long,format);        //格式化毫秒值为指定格式

// 用于实体类 param,po,dto,vo
@Override
public String toString() {
     return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE);
}


 
19- 集合和数组的处理

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.collections.CollectionUtils;

boolean ArrayUtils.isEmpty(Array);
boolean ArrayUtils.isNotEmpty(Array);

boolean CollectionUtils.isEmpty(Collection);
boolean CollectionUtils.isNotEmpty(Collection);
Collection CollectionUtils.union(a,b);            //并集
Collection CollectionUtils.intersection(a,b);    //交集
Collection CollectionUtils.disjunction(a,b);    //补集
Collection CollectionUtils.subtract(a,b);        //差集



20- 日期处理

import org.apache.commons.lang3.time.DateUtils;

Date DateUtils.parseDate(str,parsePatterns);
boolean DateUtils.isSameDay(Date,Date);            //判断两个日期是否是同一天

Date DateUtils.truncate(Date,field);            //日期截取,只取指定日期字段的值
Date DateUtils.round(Date,field);                // 日期四舍五入,和 truncate 的区别是 如果用 YEAR 当前时间是 2019-08-18 truncate 的值还是 2019 ,但 round 会得到 2020 

Date DateUtils.addDays(Date,amount);            //增加一天,这个不会修改原来的日期值
还有 addYears,addMonths,addWeeks,addHours,addMinutes,addSeconds,addMilliseconds

Date DateUtils.setDays(Date,amount);            //设置为本月的第几天
还有 setYears,setMonths,setHours,setMinutes,setSeconds,setMilliseconds

/*
计算已过去的天数,从哪儿开始算呢,根据第2个参数fragment来确定,
如现在是2014-10-23 13:27:00,那么
DateUtils.getFragmentInDays(new Date(), Calendar.MONTH)返回23,表示从当月起已经过去23天了,
DateUtils.getFragmentInDays(new Date(), Calendar.YEAR)返回296,表示从当年起已经过去296天了,
DateUtils.getFragmentInHours(new Date(), Calendar.DATE)返回13,表示从今天起已经过去13个小时了
*/
long DateUtils.getFragmentInDays(Date,fragment);    //计算已经过去的天数



21- 数字的一些处理

import org.apache.commons.lang3.math.NumberUtils;

int NumberUtils.toInt(String);
还有 toLong,toDouble,toFloat,toShort 等

boolean NumberUtils.isDigits(String);        //判断是否全由数字组成 "" 为 false
boolean NumberUtils.isNumber(String);        // 支持 0x 类的表达形式



22- 增强反射处理

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.util.ReflectionUtils;

Class<?> ClassUtils.getClass(className);
boolean ClassUtils.isInnerClass(Class<?>);            //是否是内部类
boolean ClassUtils.isPrimitiveOrWrapper(Class<?>);    //判断是否是原始类型或原始类型的包装类

List<Method> MethodUtils.getMethodsListWithAnnotation( Class<?>, Class<? extends Annotation>);
Method ReflectionUtils.findMethod(Class<?> clazz,methodName, Class<?>...);
PropertyDescriptor[] ReflectUtils.getBeanGetters(Class type);

Object MethodUtils.invokeMethod(object,methodName,args[],values[]);    //调用方法


23- IO 流,文件相关方法

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.FileSystemUtils;

String IOUtils.toString(InputStream,encoding);            //文本文件流读出字符串
List<String> IOUtils.readLines(InputStream,encoding);    //文本文件读出 List<String>
int IOUtils.copy(InputStream, OutputStream);

void FileUtils.writeStringToFile(File, String, Charset);
void FileUtils.deleteDirectory(File);

String FilenameUtils.getBaseName(filename);            //获取文件名
String FilenameUtils.getExtension(filename);        //获取扩展名
String FilenameUtils.separatorsToUnix(String path);    //转成 linux 路径分隔符

//磁盘剩余空间
long freeSpace = FileSystemUtils.freeSpace("C:/");



24- 加解密相关

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

byte[] Base64.encodeBase64(byte []);
byte[] Base64.decodeBase64(byte[]);

char [] Hex.encodeHex(byte []);
byte [] Hex.decodeHex(char []);

String DigestUtils.md5Hex(String);
String DigestUtils.shaHex(String);



25- 随机数生成

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.RandomStringUtils;

int RandomUtils.nextInt(start,end);
long RandomUtils.nextLong(start,end);

String RandomStringUtils.randomNumeric(count);
String RandomStringUtils.randomAlphabetic(count);



26-其它可以用到的工具

// 秒表

import org.apache.commons.lang3.time.StopWatch;
StopWatch stopWatch = new StopWatch();
stopWatch.start();
stopWatch.getTime();
stopWatch.stop();

//spring 获取方法参数名称

import org.springframework.core.ParameterNameDiscoverer;
ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = parameterNameDiscoverer.getParameterNames(method);

//spring 用于处理逗号分隔符的字符串列表方法

import org.springframework.util.StringUtils;
String [] StringUtils.tokenizeToStringArray(String str, String delimiters);


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值