常用工具类 (一) : Apache Commons 常用工具类整理 (全)

单于骁
2023-12-01


一、commons-lang3

引入依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

StringUtils 字符串工具类

包含判断方法:contains/containsXXX 
字符串替换方法:replace/replaceXXX 
获取子串:substring/substringXXX 
判断方法:
1、isEmpty/isNotEmpty/isBlank/isNotBlank/isNumeric/isWhitespace
2、sartsWith/startsWithAny/endsWith/endsWithIgnoreCase
索引(index):indexOf/indexOfXXX/tIndexOf/lastIndexOfXXX
处理方法:
    abbreviate 缩短 capitalise 首字母 repeat 重复 left/right/center 左右中间
    removeXXX 移除 trimXXX 去空  reverseXXX 翻转 stripXXX 移除
    defaultXXX 默认 lowerCase/upperCase deleteXXX 删除处理
    splitXXX分解处理 join 拼接

StringEscapeUtils 转义字符串工具类

StringEscapeUtils类可以对html js xml sql 等代码进行转义来防止SQL注入

escapeCsv/unescapeCsv/escapeHtml/unescapeHtml/escapeJava/unescapeJava
escapeJavaScript/unescapeJavaScript/escapeXml/unescapeXml/escapeSql

NumberUtils 数字工具类

创建数字:createXXX  创建Integer,Float,Double,Number,BigDecimal,BigInteger等数字
字符转数字:toXXX     字符串转数字:Byte,Double,Float,Int,Long,Short
判断是否数字:isDigits/isNumber
其他方法:compare,max,min,

ArrayUtils 数组工具类

添加移除:add,addAll,remove,removeElement,
拷贝:clone
判断:contains,isEmpty,isNotEmpty,isEquals,isSameLength,
其他:getLength,indexOf,lastIndexOf,nullToEmpty,reverse,subArray,
转换:toMap,toObject,toPrimitive,toString

RandomUtils 随机数工具类

nextBoolean/nextInt/nextLong/nextFloat/nextDouble

RandomStringUtils 随机字符串工具类

random/randomNumeric/randomAlphabetic/randomAscii

DateUtils 日期工具类

说明:XXX表示milisecends,seconds,minutes,hours,days,weeks,months,years
时间加减:add/addXXX 
时间设置:setXXX 
获取片段:getFragmentInXXX    获取date的1月1日0点0分0秒到指定时间的片段值
判断: isSameDay/isSameInstant/isSameLocalTime
转换: parseDate/parseDateStrictly
取模: ceiling/round/truncate
时间段:iterator   注意rangeStyle=1到4表示周范围以及偏移,5和6表示月偏移

DateFormatUtils时间格式化

格式化:format/formatUTC

DurationFormatUtils时间段格式化

formatDuration/formatDurationHMS/formatDurationISO
formatPeriod/formatPeriodISO
formatDurationWords

StopWatch 秒表

start/stop/suspend/split/resume/reset/unsplit
getSplitTime/getStartTime/getTime/
toSplitString/toString

EnumUtils 枚举工具类

getEnum/getEnumIgnoreCase/getEnumList/getEnumMap
iterator

反射工具类

ClassUtils 类工具

获取: 
    1、类和接口 :getClass/getAllInterfaces/getAllSuperclasses/getShortClassName
    2、包:getPackageName/getPackageCanonicalName
    3、方法:getPublicMethod
转换:
    1、toClass/convertClassesToClassNames/convertClassNamesToClasses/
    2、primitivesToWrappers/primitiveToWrapper/wrappersToPrimitives/wrapperToPrimitive
判断:isAssignable/isInnerClass

MethodUtils

getAccessibleMethod/getMatchingAccessibleMethod
invokeMethod/invokeStaticMethod/invokeExactMethod/invokeExactStaticMethod

FieldUtils

getField/readField/writeField
getDeclaredField/readDeclaredField/writeDeclaredField
readDeclaredStaticField/readStaticField/writeDeclaredStaticField/writeStaticField

ConstructorUtils

getAccessibleConstructor/getMatchingAccessibleConstructor
invokeConstructor/invokeExactConstructor

ObjectUtils 对象工具类

max/min/toString/identityToString/appendIdentityToString/defaultIfNull

SystemUtils 系统属性工具类

getJavaHome/getJavaIoTmpDir/getJavaVersion/getUserDir/getUserHome/
isJavaAwtHeadless/isJavaVersionAtLeast

SerializationUtils 序列化工具类

clone/deserialize/serialize

LocaleUtils 本地工具类

availableLocaleList/availableLocaleSet
countriesByLanguage
localeLookupList/toLocale/isAvailableLocale/languagesByCountry

二、commons-collecions4

引入依赖

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

CollectionUtils 集合工具类

添加/删除:addAll/addIgnoreNull/retainAll/removeAll/
获取:
	find/get/containsAny/index/size/sizeIsEmpty/select/selectRejected/subtract
	typedCollection
判断: 
	isEmpty/isNotEmpty/isFull/exists/isEqualCollection/
	isSubCollection/isProperSubCollection 
转换: 
	collect/transform/transformedCollection/predicatedCollection
	unmodifiableCollection/synchronizedCollection 
计算:cardinality/countMatches/maxSize
过滤:filter
集合:intersection/union/disjunction  交集,并集,差集
其他操作:
   reverseArray  翻转  forAllDo 给每个元素执行闭包
   getCardinalityMap 转成Map,key是元素,value是次数

ListUtils-List工具类

判断: isEqualList
集合:intersection/sum/union/retainAll 交集,并集,合集,差集
操作:removeAll/hashCodeForList
子集: typedList/subtract/fixedSizeList
转换处理:synchronizedList/unmodifiableList/predicatedList/transformedList/lazyList

SetUtils-Set集合工具类

判断:isEqualSet
转换处理:
		transformedSet/transformedSortedSet/predicatedSet/predicatedSortedSet
		unmodifiableSet/synchronizedSet/synchronizedSortedSet
		orderedSet/typedSet/typedSortedSet
操作:hashCodeForSet

MapUtils-Map工具类

获取:getObject/getString/getXXX/getXXXValue  获取指定类型值,getXXXValue 如果没有值则默认值
子集:fixedSizeMap/fixedSizeSortedMap/typedMap/typedSortedMap
判断:isEmpty/isNotEmpty
转换:
	predicatedMap/predicatedSortedMap/transformedMap/transformedSortedMap/
	synchronizedMap/synchronizedSortedMap/
	unmodifiableMap/unmodifiableSortedMap/multiValueMap/orderedMap
	toMap/toProperties/lazyMap/lazySortedMap
添加移除:safeAddToMap/putAll
其他操作:invertMap/debugPrint/verbosePrint

三、commons-beanutils

引入依赖

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

BeanUtils/BeanUtilsBean

拷贝: cloneBean/copyProperties/copyProperty
获取:getArrayProperty/getSimpleProperty/getProperty
其他操作:setProperty设置属性 populate将Bean设置到Map中  describe将Bean转成Map  

PropertyUtils类

判断:isReadable/isWriteable
获取:
	getProperty/getSimpleProperty/getPropertyType 
	getReadMethod/getWriteMethod/getIndexedProperty/setIndexedProperty
	getMappedProperty/setMappedProperty/getNestedProperty/setNestedProperty  
	getPropertyDescriptor/getPropertyEditorClass
拷贝和设置:copyProperties/setProperty/setSimpleProperty /clearDescriptors       

四、commons-io

引入依赖

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

FileUtils 文件操作工具类

文件夹操作: 
 copyDirectory/deleteDirectory/cleanDirectory/getTempDirectory/getTempDirectoryPath
 moveDirectory/moveDirectoryToDirectory/moveFileToDirectory/moveToDirectory
 forceMkdir/getUserDirectory/getUserDirectoryPath
文件操作:
	touch/copyFile/copyURLToFile/moveFile/deleteQuietly/forceDelete/forceDeleteOnExit
	toFile/toFiles/toURLs
	isFileNewer/isFileOlder
	readLines/readFileToByteArray/readFileToString/lineIterator/openOutputStream
	write/writeLines/writeByteArrayToFile/writeStringToFile/openInputStream
其他操作:
    iterateFiles/listFiles/contentEquals/sizeOf/sizeOfDirectory

IOUtils 流操作工具类

读操作:lineIterator/read/readLines
写操作:write/writeLines
转换: toInputStream/toBufferedInputStream/toByteArray/toCharArray/toString
其他操作:copy/copyLarge/contentEquals/skip/skipFully/closeQuietly

FilenameUtils 文件名工具类

获取:
	getName/getBaseName/getPrefix/getPrefixLength/getExtension
	getPath/getFullPath/getFullPathNoEndSeparator/getPathNoEndSeparator
判断:
	isExtension/equals/equalsNormalized/equalsOnSystem
其他操作:
	removeExtension/indexOfExtension
	separatorsToSystem/separatorsToUnix/separatorsToWindows
	indexOfLastSeparator

其他工具类

文件比较器:
    CompositeFileComparator/DefaultFileComparator/DirectoryFileComparator
    ExtensionFileComparator/LastModifiedFileComparator/NameFileComparator
    PathFileComparator/PathFileComparator
文件过滤器:
    AgeFileFilter/AndFileFilter/CanReadFileFilter/CanWriteFileFilter
    DelegateFileFilter/DirectoryFileFilter/EmptyFileFilter/FalseFileFilter/FileFileFilter
    FileFilterUtils/HiddenFileFilter/MagicNumberFileFilter/NameFileFilter/NotFileFilter
    OrFileFilter/PrefixFileFilter/RegexFileFilter/SizeFileFilter/SuffixFileFilter
    TrueFileFilter/WildcardFileFilter/WildcardFilter
 类似资料: