refactor(mingli-utils):重构集合工具类并添加新功能

- 重写 Collection 类,使用 Kotlin 语法和特性优化代码结构
- 添加新方法以支持数组和集合之间的转换
- 新增 CopyOnWriteArrayList、Stack 和 TreeSet 相关方法
-优化现有方法,提高代码可读性和性能
- 删除未使用的 ForEach 导入
-调整 build.gradle.kts 中的依赖项
This commit is contained in:
2025-09-15 09:30:41 +08:00
parent d6a2117b58
commit dc129c016f
37 changed files with 1507 additions and 19308 deletions
+4 -5
View File
@@ -16,17 +16,16 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Main.kt
* LastUpdate 2025-09-14 22:05:03
* LastUpdate 2025-09-15 08:56:35
* UpdateUser MingLiPro
*/
@file:JvmName("Main")
package com.mingliqiye.utils
import com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration
fun main() {
AutoConfiguration.printBanner()
}
fun test() {
}
@@ -16,14 +16,13 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ByteUtils.kt
* LastUpdate 2025-09-14 19:28:38
* LastUpdate 2025-09-15 00:07:22
* UpdateUser MingLiPro
*/
@file:JvmName("ByteUtils")
package com.mingliqiye.utils.bytes
import com.mingliqiye.utils.collection.Lists
import com.mingliqiye.utils.stream.SuperStream
const val ESC_ASC: Byte = 0x10
@@ -42,7 +41,7 @@ const val ESC_RESERVED: Byte = 0x06
* @return 包含每个字节对应十六进制字符串的列表
*/
fun ByteArray.getByteArrayString(): MutableList<String> {
return Lists.toList(this)!!.stream()
return this.toList().stream()
.map { a -> String.format("0X%02X", a!!.toInt() and 0xFF) }
.collect(SuperStream.Collectors.toList())
}
@@ -15,8 +15,8 @@
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile CloneUtil.kt
* LastUpdate 2025-09-14 19:53:41
* CurrentFile CloneUtils.kt
* LastUpdate 2025-09-15 09:30:37
* UpdateUser MingLiPro
*/
@file:JvmName("CloneUtils")
@@ -0,0 +1,470 @@
/*
* Copyright 2025 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Collection.kt
* LastUpdate 2025-09-15 09:30:37
* UpdateUser MingLiPro
*/
@file:JvmName("Collections")
package com.mingliqiye.utils.collection
import com.mingliqiye.utils.stream.SuperStream
import java.util.*
inline fun <reified T> Collection<T>.toArray(): Array<T> {
return arrayOf(*this.toTypedArray())
}
inline fun <reified T, V> Collection<T>.toMap(noinline v: (T) -> V): Map<T, V> {
return this.stream().collect(
SuperStream.Collectors.toMap(
SuperStream.Collectors::getThis, v
)
)
}
inline fun <reified T, V, K> Collection<T>.toMap(noinline k: (T) -> K, noinline v: (T) -> V): Map<K, V> {
return this.stream().collect(
SuperStream.Collectors.toMap(
k, v
)
)
}
fun <T> toSet(array: Array<T>): Set<T> {
return array.toSet()
}
inline fun <reified T> Collection<T>.getFirst(): T? {
if (this.isEmpty()) {
return null
}
if (this is MutableList<T>) {
return this.first()
}
return this.iterator().next()
}
inline fun <reified T> Array<T>.getFirst(): T? {
if (this.isEmpty()) {
return null
}
return this.first()
}
inline fun <reified T> Collection<T>.getLast(): T? {
if (this.isEmpty()) {
return null
}
if (this is MutableList<T>) {
return this.last()
}
var lastElement: T? = null
for (element in this) {
lastElement = element
}
return lastElement
}
inline fun <reified T> Array<T>.getLast(): T? {
if (this.isEmpty()) {
return null
}
return this.last()
}
inline fun <reified T> Collection<T>.getOrDefault(
index: Int, defaultValue: T
): T {
if (!(!this.isEmpty() && index < this.size)) {
return defaultValue
}
if (this is List<T>) {
return this[index]
}
var i = 0
for (element in this) {
if (i == index) {
return element
}
i++
}
return defaultValue
}
fun <T> newArrayList(): ArrayList<T> {
return ArrayList()
}
fun <T> newArrayList(size: Int): ArrayList<T> {
return ArrayList()
}
fun <T> newArrayList(vararg elements: T): ArrayList<T> {
return newArrayList(elements.asList())
}
fun <T> Collection<T>.newArrayLists(): ArrayList<T> {
return newArrayList(this)
}
fun <T> newArrayLists(elements: Array<T>): ArrayList<T> {
return newArrayList(elements.asList())
}
fun <T> newArrayList(elements: Collection<T>): ArrayList<T> {
return ArrayList(elements.toList())
}
fun <T> newArrayList(elements: Iterable<T>): ArrayList<T> {
return newArrayList(elements.toList())
}
fun <T> newArrayList(elements: Sequence<T>): ArrayList<T> {
return newArrayList(elements.toList())
}
fun <T> newLinkedList(): LinkedList<T> {
return LinkedList()
}
fun <T> newLinkedList(vararg elements: T): LinkedList<T> {
val list = newLinkedList<T>()
list.addAll(elements.asList())
return list
}
fun <T> newLinkedList(elements: Collection<T>): LinkedList<T> {
val list = newLinkedList<T>()
list.addAll(elements)
return list
}
fun <T> newLinkedList(elements: Iterable<T>): LinkedList<T> {
val list = newLinkedList<T>()
for (element in elements) {
list.add(element)
}
return list
}
fun <T> newLinkedList(elements: Sequence<T>): LinkedList<T> {
return newLinkedList(elements.toList())
}
fun <T> newVector(): Vector<T> {
return Vector()
}
fun <T> newVector(vararg elements: T): Vector<T> {
val vector = newVector<T>()
vector.addAll(elements.asList())
return vector
}
fun <T> newVector(elements: Collection<T>): Vector<T> {
val vector = newVector<T>()
vector.addAll(elements)
return vector
}
fun <T> newVector(elements: Iterable<T>): Vector<T> {
val vector = newVector<T>()
for (element in elements) {
vector.add(element)
}
return vector
}
fun <T> newVector(elements: Sequence<T>): Vector<T> {
return newVector(elements.toList())
}
fun <T> newHashSet(): HashSet<T> {
return HashSet()
}
fun <T> newHashSet(size: Int): HashSet<T> {
return HashSet(size)
}
fun <T> newHashSet(vararg elements: T): HashSet<T> {
val set = newHashSet<T>()
set.addAll(elements.asList())
return set
}
fun <T> newHashSet(elements: Collection<T>): HashSet<T> {
val set = newHashSet<T>()
set.addAll(elements)
return set
}
fun <T> newHashSet(elements: Iterable<T>): HashSet<T> {
val set = newHashSet<T>()
for (element in elements) {
set.add(element)
}
return set
}
fun <T> newHashSet(elements: Sequence<T>): HashSet<T> {
return newHashSet(elements.toSet())
}
fun <T> newLinkedHashSet(): LinkedHashSet<T> {
return LinkedHashSet()
}
fun <T> newLinkedHashSet(size: Int): LinkedHashSet<T> {
return LinkedHashSet(size)
}
fun <T> newLinkedHashSet(vararg elements: T): LinkedHashSet<T> {
val set = newLinkedHashSet<T>()
set.addAll(elements.asList())
return set
}
fun <T> newLinkedHashSet(elements: Collection<T>): LinkedHashSet<T> {
val set = newLinkedHashSet<T>()
set.addAll(elements)
return set
}
fun <T> newLinkedHashSet(elements: Iterable<T>): LinkedHashSet<T> {
val set = newLinkedHashSet<T>()
for (element in elements) {
set.add(element)
}
return set
}
fun <T> newLinkedHashSet(elements: Sequence<T>): LinkedHashSet<T> {
return newLinkedHashSet(elements.toSet())
}
fun <T : Comparable<T>> newTreeSet(): TreeSet<T> {
return TreeSet()
}
fun <T : Comparable<T>> newTreeSet(vararg elements: T): TreeSet<T> {
val set = newTreeSet<T>()
set.addAll(elements.asList())
return set
}
fun <T : Comparable<T>> newTreeSet(elements: Collection<T>): TreeSet<T> {
val set = newTreeSet<T>()
set.addAll(elements)
return set
}
fun <T : Comparable<T>> newTreeSet(elements: Iterable<T>): TreeSet<T> {
val set = newTreeSet<T>()
for (element in elements) {
set.add(element)
}
return set
}
fun <T : Comparable<T>> newTreeSet(elements: Sequence<T>): TreeSet<T> {
return newTreeSet(elements.toSet())
}
fun newArrayLists(elements: ByteArray): ArrayList<Byte> {
return ArrayList(elements.toList())
}
fun newArrayLists(elements: ShortArray): ArrayList<Short> {
return ArrayList(elements.toList())
}
fun newArrayLists(elements: IntArray): ArrayList<Int> {
return ArrayList(elements.toList())
}
fun newArrayLists(elements: LongArray): ArrayList<Long> {
return ArrayList(elements.toList())
}
fun newArrayLists(elements: FloatArray): ArrayList<Float> {
return ArrayList(elements.toList())
}
fun newArrayLists(elements: DoubleArray): ArrayList<Double> {
return ArrayList(elements.toList())
}
fun newArrayLists(elements: BooleanArray): ArrayList<Boolean> {
return ArrayList(elements.toList())
}
fun newArrayLists(elements: CharArray): ArrayList<Char> {
return ArrayList(elements.toList())
}
fun <T> newCopyOnWriteArrayList(): java.util.concurrent.CopyOnWriteArrayList<T> {
return java.util.concurrent.CopyOnWriteArrayList()
}
fun <T> newCopyOnWriteArrayList(vararg elements: T): java.util.concurrent.CopyOnWriteArrayList<T> {
return java.util.concurrent.CopyOnWriteArrayList(elements.asList())
}
fun <T> newCopyOnWriteArrayList(elements: Collection<T>): java.util.concurrent.CopyOnWriteArrayList<T> {
return java.util.concurrent.CopyOnWriteArrayList(elements)
}
fun <T> newStack(): Stack<T> {
return Stack()
}
fun <T> newStack(vararg elements: T): Stack<T> {
val stack = newStack<T>()
stack.addAll(elements.asList())
return stack
}
fun <T> newStack(elements: Collection<T>): Stack<T> {
val stack = newStack<T>()
stack.addAll(elements)
return stack
}
fun <T> newTreeSet(comparator: Comparator<T>): TreeSet<T> {
return TreeSet(comparator)
}
fun <T> newTreeSet(comparator: Comparator<T>, vararg elements: T): TreeSet<T> {
val set = newTreeSet(comparator)
set.addAll(elements.asList())
return set
}
fun <T> newTreeSet(comparator: Comparator<T>, elements: Collection<T>): TreeSet<T> {
val set = newTreeSet(comparator)
set.addAll(elements)
return set
}
fun <T> newTreeSet(comparator: Comparator<T>, elements: Iterable<T>): TreeSet<T> {
val set = newTreeSet(comparator)
for (element in elements) {
set.add(element)
}
return set
}
fun <T> newTreeSet(comparator: Comparator<T>, elements: Sequence<T>): TreeSet<T> {
return newTreeSet(comparator, elements.toSet())
}
fun <T> Collection<T>.newCopyOnWriteArrayLists(): java.util.concurrent.CopyOnWriteArrayList<T> {
return java.util.concurrent.CopyOnWriteArrayList(this)
}
fun <T> Collection<T>.newStacks(): Stack<T> {
val stack = Stack<T>()
stack.addAll(this)
return stack
}
fun <T> Collection<T>.newTreeSets(): TreeSet<T> where T : Comparable<T> {
val set = TreeSet<T>()
set.addAll(this)
return set
}
fun <T> Collection<T>.newTreeSets(comparator: Comparator<T>): TreeSet<T> {
val set = TreeSet(comparator)
set.addAll(this)
return set
}
fun toArray(list: List<Byte>): ByteArray {
val arr = ByteArray(list.size)
for (i in list.indices) {
arr[i] = list[i]
}
return arr
}
fun toArray(list: List<Short>): ShortArray {
val arr = ShortArray(list.size)
for (i in list.indices) {
arr[i] = list[i]
}
return arr
}
fun toArray(list: List<Int>): IntArray {
val arr = IntArray(list.size)
for (i in list.indices) {
arr[i] = list[i]
}
return arr
}
fun toArray(list: List<Long>): LongArray {
val arr = LongArray(list.size)
for (i in list.indices) {
arr[i] = list[i]
}
return arr
}
fun toArray(list: List<Float>): FloatArray {
val arr = FloatArray(list.size)
for (i in list.indices) {
arr[i] = list[i]
}
return arr
}
fun toArray(list: List<Double>): DoubleArray {
val arr = DoubleArray(list.size)
for (i in list.indices) {
arr[i] = list[i]
}
return arr
}
fun toArray(list: List<Boolean>): BooleanArray {
val arr = BooleanArray(list.size)
for (i in list.indices) {
arr[i] = list[i]
}
return arr
}
fun toArray(list: List<Char>): CharArray {
val arr = CharArray(list.size)
for (i in list.indices) {
arr[i] = list[i]
}
return arr
}
@@ -0,0 +1,104 @@
/*
* Copyright 2025 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile IsChanged.kt
* LastUpdate 2025-09-15 09:30:37
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.concurrent
import java.util.*
import java.util.concurrent.atomic.AtomicReference
/**
* IsChanged 类提供了一个线程安全的包装器,用于检测值是否发生变化。
* 它基于 AtomicReference 实现,适用于需要监控数据变更的并发场景。
*
* @param T 泛型类型,表示被包装的数据类型
* @author MingLiPro
*/
class IsChanged<T> {
/**
* 使用 AtomicReference 来保证对数据的原子操作
*/
private val atomicReferenceData: AtomicReference<T> = AtomicReference()
/**
* 默认构造函数,初始化数据为 null
*/
constructor() : this(null)
/**
* 带参数的构造函数,使用指定的初始值初始化
*
* @param data 初始数据值
*/
constructor(data: T?) : super() {
atomicReferenceData.set(data)
}
/**
* 设置新的数据值,不检查是否发生变化
*
* @param data 要设置的新数据值
*/
fun set(data: T) {
atomicReferenceData.set(data)
}
/**
* 获取当前数据值
*
* @return 当前数据值
*/
fun get(): T? {
return atomicReferenceData.get()
}
/**
* 设置新的数据值并返回旧的数据值
*
* @param data 要设置的新数据值
* @return 设置前的旧数据值
*/
fun setAndGet(data: T): T? {
return atomicReferenceData.getAndSet(data)
}
/**
* 设置新的数据值,如果新值与当前值不同则更新并返回 true,否则返回 false
* 使用 CAS(Compare-And-Swap) 操作确保线程安全
*
* @param data 要设置的新数据值
* @return 如果值发生变化返回 true,否则返回 false
*/
fun setAndChanged(data: T): Boolean {
var currentData: T?
do {
currentData = get()
// 如果新值与当前值相等,则认为没有变化,直接返回 false
if (Objects.equals(data, currentData)) {
return false
}
// 使用 CAS 操作尝试更新值,如果失败则重试
} while (!atomicReferenceData.compareAndSet(currentData, data))
// 成功更新值,返回 true 表示发生了变化
return true
}
}
@@ -0,0 +1,98 @@
/*
* Copyright 2025 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ThreadLocalDataHolder.kt
* LastUpdate 2025-09-15 09:15:14
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.data
/**
* 泛型线程局部变量持有器
*
* 封装了 ThreadLocal 的常用操作,提供更便捷的 API 来管理线程本地变量。
*
* @param T 存储的数据类型
* @author MingLiPro
*/
class ThreadLocalDataHolder<T> {
private val threadLocal: ThreadLocal<T?> = ThreadLocal()
/**
* 获取当前线程存储的值
*
* @return 当前线程存储的值,如果没有则返回null
*/
fun get(): T? {
return threadLocal.get()
}
/**
* 设置当前线程的值
*
* @param value 要存储的值
*/
fun set(value: T) {
threadLocal.set(value)
}
/**
* 移除当前线程存储的值
*
* 防止内存泄漏,使用完毕后应调用此方法清理资源。
*/
fun remove() {
threadLocal.remove()
}
/**
* 获取当前线程存储的值,如果不存在则返回默认值
*
* @param defaultValue 默认值
* @return 当前线程存储的值或默认值
*/
fun getOrDefault(defaultValue: T): T {
val value = threadLocal.get()
return value ?: defaultValue
}
/**
* 安全获取值(避免NPE)
*
* 在某些异常情况下防止抛出异常,直接返回 null。
*
* @return 值或null
*/
fun safeGet(): T? {
return try {
threadLocal.get()
} catch (e: Exception) {
null
}
}
/**
* 检查当前线程是否有值
*
* @return 是否有值
*/
fun isPresent(): Boolean {
return threadLocal.get() != null
}
}
@@ -0,0 +1,346 @@
/*
* Copyright 2025 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile FileUtils.kt
* LastUpdate 2025-09-15 09:12:47
* UpdateUser MingLiPro
*/
@file:JvmName("FileUtils")
package com.mingliqiye.utils.file
import com.mingliqiye.utils.path.OsPath
import java.io.IOException
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
/**
* 默认字符集
*/
var DEFAULT_CHARSET: Charset = StandardCharsets.UTF_8
/**
* 读取文件内容为字符串
*
* @param filePath 文件路径
* @return 文件内容字符串
* @throws IOException 读取文件时发生错误
*/
@Throws(IOException::class)
fun readFileToString(filePath: String): String {
return readFileToString(filePath, DEFAULT_CHARSET)
}
/**
* 读取文件内容为字符串
*
* @param filePath 文件路径
* @param charset 字符集
* @return 文件内容字符串
* @throws IOException 读取文件时发生错误
*/
@Throws(IOException::class)
fun readFileToString(filePath: String, charset: Charset): String {
val path = OsPath.of(filePath)
val bytes = Files.readAllBytes(path)
return String(bytes, charset)
}
/**
* 将字符串写入文件
*
* @param filePath 文件路径
* @param content 要写入的内容
* @throws IOException 写入文件时发生错误
*/
@Throws(IOException::class)
fun writeStringToFile(filePath: String, content: String) {
writeStringToFile(filePath, content, DEFAULT_CHARSET)
}
/**
* 将字符串写入文件
*
* @param filePath 文件路径
* @param content 要写入的内容
* @param charset 字符集
* @throws IOException 写入文件时发生错误
*/
@Throws(IOException::class)
fun writeStringToFile(filePath: String, content: String, charset: Charset) {
val path = Paths.get(filePath)
path.parent?.let { Files.createDirectories(it) }
Files.write(path, content.toByteArray(charset))
}
/**
* 读取文件内容为字符串列表(按行分割)
*
* @param filePath 文件路径
* @return 文件内容按行分割的字符串列表
* @throws IOException 读取文件时发生错误
*/
@Throws(IOException::class)
fun readLines(filePath: String): List<String> {
return readLines(filePath, DEFAULT_CHARSET)
}
/**
* 读取文件内容为字符串列表(按行分割)
*
* @param filePath 文件路径
* @param charset 字符集
* @return 文件内容按行分割的字符串列表
* @throws IOException 读取文件时发生错误
*/
@Throws(IOException::class)
fun readLines(filePath: String, charset: Charset): List<String> {
val path = Paths.get(filePath)
return Files.readAllLines(path, charset)
}
/**
* 将字符串列表写入文件(每行一个元素)
*
* @param filePath 文件路径
* @param lines 要写入的行内容列表
* @throws IOException 写入文件时发生错误
*/
@Throws(IOException::class)
fun writeLines(filePath: String, lines: List<String>) {
writeLines(filePath, lines, DEFAULT_CHARSET)
}
/**
* 将字符串列表写入文件(每行一个元素)
*
* @param filePath 文件路径
* @param lines 要写入的行内容列表
* @param charset 字符集
* @throws IOException 写入文件时发生错误
*/
@Throws(IOException::class)
fun writeLines(filePath: String, lines: List<String>, charset: Charset) {
val path = Paths.get(filePath)
Files.createDirectories(path.parent)
Files.write(path, lines, charset)
}
/**
* 复制文件
*
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
* @throws IOException 复制文件时发生错误
*/
@Throws(IOException::class)
fun copyFile(sourcePath: String, targetPath: String) {
val source = Paths.get(sourcePath)
val target = Paths.get(targetPath)
Files.createDirectories(target.parent)
Files.copy(source, target)
}
/**
* 删除文件
*
* @param filePath 文件路径
* @return 如果文件删除成功返回true,否则返回false
*/
fun deleteFile(filePath: String): Boolean {
return try {
val path = Paths.get(filePath)
Files.deleteIfExists(path)
} catch (e: IOException) {
false
}
}
/**
* 检查文件是否存在
*
* @param filePath 文件路径
* @return 如果文件存在返回true,否则返回false
*/
fun exists(filePath: String): Boolean {
val path = Paths.get(filePath)
return Files.exists(path)
}
/**
* 获取文件大小
*
* @param filePath 文件路径
* @return 文件大小(字节),如果文件不存在返回-1
*/
fun getFileSize(filePath: String): Long {
return try {
val path = Paths.get(filePath)
Files.size(path)
} catch (e: IOException) {
-1
}
}
/**
* 创建目录
*
* @param dirPath 目录路径
* @return 如果目录创建成功返回true,否则返回false
*/
fun createDirectory(dirPath: String): Boolean {
return try {
val path = Paths.get(dirPath)
Files.createDirectories(path)
true
} catch (e: IOException) {
false
}
}
/**
* 获取文件扩展名
*
* @param fileName 文件名
* @return 文件扩展名(不包含点号),如果无扩展名返回空字符串
*/
fun getFileExtension(fileName: String): String {
if (fileName.isEmpty()) {
return ""
}
val lastDotIndex = fileName!!.lastIndexOf('.')
return if (lastDotIndex == -1 || lastDotIndex == fileName.length - 1) {
""
} else fileName.substring(lastDotIndex + 1)
}
/**
* 获取不带扩展名的文件名
*
* @param fileName 文件名
* @return 不带扩展名的文件名
*/
fun getFileNameWithoutExtension(fileName: String): String {
if (fileName.isEmpty()) {
return ""
}
val lastDotIndex = fileName!!.lastIndexOf('.')
return if (lastDotIndex == -1) {
fileName
} else fileName.substring(0, lastDotIndex)
}
/**
* 读取文件内容为字节数组
*
* @param filePath 文件路径
* @return 文件内容的字节数组
* @throws IOException 读取文件时发生错误
*/
@Throws(IOException::class)
fun readFileToByteArray(filePath: String): ByteArray {
val path = Paths.get(filePath)
return Files.readAllBytes(path)
}
/**
* 将字节数组写入文件
*
* @param filePath 文件路径
* @param data 要写入的字节数据
* @throws IOException 写入文件时发生错误
*/
@Throws(IOException::class)
fun writeByteArrayToFile(filePath: String, data: ByteArray) {
val path = Paths.get(filePath)
Files.createDirectories(path.parent)
Files.write(path, data)
}
/**
* 将字节数组追加到文件末尾
*
* @param filePath 文件路径
* @param data 要追加的字节数据
* @throws IOException 追加数据时发生错误
*/
@Throws(IOException::class)
fun appendByteArrayToFile(filePath: String, data: ByteArray) {
val path = Paths.get(filePath)
Files.createDirectories(path.parent)
Files.write(
path, data, StandardOpenOption.CREATE, StandardOpenOption.APPEND
)
}
/**
* 分块读取大文件为字节数组列表
*
* @param filePath 文件路径
* @param chunkSize 每块大小(字节)
* @return 文件内容按指定大小分割的字节数组列表
* @throws IOException 读取文件时发生错误
*/
@Throws(IOException::class)
fun readFileToByteArrayChunks(filePath: String, chunkSize: Int): List<ByteArray> {
val chunks = mutableListOf<ByteArray>()
val path = Paths.get(filePath)
Files.newInputStream(path).use { inputStream ->
val buffer = ByteArray(chunkSize)
var bytesRead: Int
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
val chunk = ByteArray(bytesRead)
System.arraycopy(buffer, 0, chunk, 0, bytesRead)
chunks.add(chunk)
}
}
return chunks
}
/**
* 将字节数组列表写入文件
*
* @param filePath 文件路径
* @param chunks 字节数组列表
* @throws IOException 写入文件时发生错误
*/
@Throws(IOException::class)
fun writeByteArrayChunksToFile(filePath: String, chunks: List<ByteArray>) {
val path = Paths.get(filePath)
Files.createDirectories(path.parent)
Files.newOutputStream(path).use { outputStream ->
for (chunk in chunks) {
outputStream.write(chunk)
}
}
}
@@ -0,0 +1,63 @@
/*
* Copyright 2025 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Response.kt
* LastUpdate 2025-09-15 09:04:05
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.http
import com.mingliqiye.utils.time.DateTime
import com.mingliqiye.utils.time.Formatter
data class Response<T>(
val time: String,
var message: String,
var data: T?,
var statusCode: Int
) {
companion object {
@JvmStatic
fun <T> ok(data: T): Response<T?> {
return Response(DateTime.now().format(Formatter.STANDARD_DATETIME_MILLISECOUND7), "操作成功", data, 200)
}
@JvmStatic
fun <T> ok(message: String): Response<T?> {
return Response(DateTime.now().format(Formatter.STANDARD_DATETIME_MILLISECOUND7), message, null, 200)
}
}
fun setMessage(message: String): Response<T> {
this.message = message
return this
}
fun setData(data: T): Response<T?> {
this.data = data
return ok(this.data)
.setMessage(this.message)
.setStatusCode(this.statusCode)
}
fun setStatusCode(statusCode: Int): Response<T> {
this.statusCode = statusCode
return this
}
}
@@ -0,0 +1,167 @@
/*
* Copyright 2025 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Maps.kt
* LastUpdate 2025-09-15 08:33:24
* UpdateUser MingLiPro
*/
@file:JvmName("Maps")
package com.mingliqiye.utils.map
import java.util.*
import java.util.concurrent.ConcurrentHashMap
fun <K, V> newHashMap(vararg elements: Pair<K, V>): HashMap<K, V> {
val map = HashMap<K, V>()
for (element in elements) {
map[element.first] = element.second
}
return map
}
fun <K, V> newHashMap(size: Int): HashMap<K, V> {
return HashMap(size)
}
fun <K, V> newHashMap(vararg elements: Map.Entry<K, V>): HashMap<K, V> {
val map = HashMap<K, V>()
for (element in elements) {
map[element.key] = element.value
}
return map
}
fun <K, V> newConcurrentHashMap(vararg elements: Map.Entry<K, V>): ConcurrentHashMap<K, V> {
val map = newConcurrentHashMap<K, V>()
for (element in elements) {
map[element.key] = element.value
}
return map
}
fun <K, V> newLinkedHashMap(vararg elements: Map.Entry<K, V>): LinkedHashMap<K, V> {
val map = newLinkedHashMap<K, V>()
for (element in elements) {
map[element.key] = element.value
}
return map
}
fun <K, V> newHashtable(vararg elements: Map.Entry<K, V>): Hashtable<K, V> {
val map = newHashtable<K, V>()
for (element in elements) {
map[element.key] = element.value
}
return map
}
fun <K : Comparable<K>, V> newTreeMap(vararg elements: Map.Entry<K, V>): TreeMap<K, V> {
val map = newTreeMap<K, V>()
for (element in elements) {
map[element.key] = element.value
}
return map
}
inline fun <reified K, reified V> Map<K, V>.newHashMap(): HashMap<K, V> {
return HashMap(this)
}
fun <K, V> newLinkedHashMap(): LinkedHashMap<K, V> {
return LinkedHashMap()
}
fun <K, V> newLinkedHashMap(size: Int): LinkedHashMap<K, V> {
return LinkedHashMap(size)
}
fun <K, V> newLinkedHashMap(vararg elements: Pair<K, V>): LinkedHashMap<K, V> {
val map = newLinkedHashMap<K, V>()
for (element in elements) {
map[element.first] = element.second
}
return map
}
inline fun <reified K, reified V> Map<K, V>.newLinkedHashMap(): LinkedHashMap<K, V> {
return LinkedHashMap(this)
}
fun <K : Comparable<K>, V> newTreeMap(): TreeMap<K, V> {
return TreeMap()
}
fun <K : Comparable<K>, V> newTreeMap(vararg elements: Pair<K, V>): TreeMap<K, V> {
val map = newTreeMap<K, V>()
for (element in elements) {
map[element.first] = element.second
}
return map
}
inline fun <reified K : Comparable<K>, reified V> Map<K, V>.newTreeMap(): TreeMap<K, V> {
return TreeMap(this)
}
fun <K, V> newHashtable(): Hashtable<K, V> {
return Hashtable()
}
fun <K, V> newHashtable(size: Int): Hashtable<K, V> {
return Hashtable(size)
}
fun <K, V> newHashtable(vararg elements: Pair<K, V>): Hashtable<K, V> {
val map = newHashtable<K, V>()
for (element in elements) {
map[element.first] = element.second
}
return map
}
inline fun <reified K, reified V> Map<K, V>.newHashtable(): Hashtable<K, V> {
val hashtable = Hashtable<K, V>()
hashtable.putAll(this)
return hashtable
}
fun <K, V> newConcurrentHashMap(): ConcurrentHashMap<K, V> {
return ConcurrentHashMap()
}
fun <K, V> newConcurrentHashMap(size: Int): ConcurrentHashMap<K, V> {
return ConcurrentHashMap(size)
}
fun <K, V> newConcurrentHashMap(vararg elements: Pair<K, V>): ConcurrentHashMap<K, V> {
val map = newConcurrentHashMap<K, V>()
for (element in elements) {
map[element.first] = element.second
}
return map
}
inline fun <reified K, reified V> Map<K, V>.newConcurrentHashMap(): ConcurrentHashMap<K, V> {
return ConcurrentHashMap(this)
}
fun <K, V> ofEntries(entries: List<MutableMap.MutableEntry<K, V>>): Map<K, V> {
return entries.associate { it.key to it.value }
}
@@ -0,0 +1,105 @@
/*
* Copyright 2025 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile OsPath.kt
* LastUpdate 2025-09-15 08:59:15
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.path
import java.io.File
import java.net.URI
import java.nio.file.*
import java.util.*
import java.util.function.Consumer
class OsPath private constructor(private val path: Path) : Path by path {
companion object {
@JvmStatic
fun of(path: String): OsPath {
return of(Paths.get(path))
}
@JvmStatic
fun of(path: Path): OsPath {
return OsPath(path)
}
@JvmStatic
fun of(uri: URI): OsPath {
return OsPath(Paths.get(uri))
}
@JvmStatic
fun of(file: File): OsPath {
return OsPath(file.toPath())
}
@JvmStatic
fun getCwd(): OsPath {
return OsPath(Paths.get(""))
}
}
override fun getParent(): Path? {
var parent = path.parent
if (parent == null) {
parent = path.toAbsolutePath().parent
}
return parent
}
override fun toRealPath(vararg options: LinkOption): Path {
return OsPath(path.toRealPath(*options))
}
override fun register(watcher: WatchService, vararg events: WatchEvent.Kind<*>): WatchKey {
return path.register(watcher, *events)
}
override fun register(
watcher: WatchService,
events: Array<out WatchEvent.Kind<*>>,
vararg modifiers: WatchEvent.Modifier
): WatchKey {
return path.register(watcher, events, *modifiers)
}
override fun iterator(): MutableIterator<Path> {
return path.iterator()
}
override fun compareTo(other: Path): Int {
return path.compareTo(other)
}
override fun toString(): String {
return path.toString()
}
override fun forEach(action: Consumer<in Path>) {
path.forEach(action)
}
override fun spliterator(): Spliterator<Path> {
return path.spliterator()
}
}
@@ -16,14 +16,13 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile RandomBytes.kt
* LastUpdate 2025-09-12 17:11:19
* LastUpdate 2025-09-15 00:08:18
* UpdateUser MingLiPro
*/
@file:JvmName("RandomBytes")
package com.mingliqiye.utils.random
import com.mingliqiye.utils.collection.ForEach
import com.mingliqiye.utils.iterator.Range
/**
@@ -33,9 +32,7 @@ import com.mingliqiye.utils.iterator.Range
*/
fun randomBytes(length: Int): ByteArray {
val bytes = ByteArray(length)
ForEach.forEach(
Range(0, length - 1)
) { i: Int -> bytes[i] = randomByte(0x00.toByte(), 0xff.toByte()) }
Range(0, length - 1).forEach { i: Int -> bytes[i] = randomByte(0x00.toByte(), 0xff.toByte()) }
return bytes
}
@@ -16,13 +16,12 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile AutoConfiguration.kt
* LastUpdate 2025-09-14 22:09:46
* LastUpdate 2025-09-15 08:51:52
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.collection.ForEach
import com.mingliqiye.utils.logger.mingLiLoggerFactory
import com.mingliqiye.utils.system.getJdkVersion
import com.mingliqiye.utils.time.DateTime
@@ -47,8 +46,6 @@ open class AutoConfiguration {
"| $$ |\\$ /$$ |$$ | $$ | $$ | $$ | $$\\ $$ | |\n" +
"| $$ | \\_/ $$ |$$$$$$$$\\\\$$$$$$ | $$ | \\$$$$$$ | |\n" +
"| \\__| \\__|\\________|\\______/ \\__| \\______/ |\n"
private var banner2: String? = null
private val log = mingLiLoggerFactory.getLogger("MingliUtils-AutoConfiguration")
fun printBanner() {
@@ -68,7 +65,7 @@ open class AutoConfiguration {
val da = metaData.toString().split("\n").toMutableList()
da.add("time=" + DateTime.now().format(Formatter.STANDARD_DATETIME_MILLISECOUND7))
da.add("jdkRuntime=" + getJdkVersion())
ForEach.forEach(da) { s: String, _: Int ->
da.forEach { s: String ->
val d = s.trim { it <= ' ' }.split("=".toRegex(), 2).toTypedArray()
if (d.size >= 2) {
val content = "| " + d[0] + ": " + d[1]
@@ -91,8 +88,7 @@ open class AutoConfiguration {
} catch (e: IOException) {
e.printStackTrace()
}
banner2 = bannerBuilder.toString()
println(banner2)
println(bannerBuilder.toString().trim())
println("---------------------------------------------------------")
}
}
@@ -0,0 +1,58 @@
/*
* Copyright 2025 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Converters.kt
* LastUpdate 2025-09-15 09:19:48
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.converters
import com.mingliqiye.utils.time.DateTime
import com.mingliqiye.utils.time.Formatter
import com.mingliqiye.utils.uuid.UUID
import com.mingliqiye.utils.uuid.UUID.Companion.of
import org.springframework.core.convert.converter.Converter
import org.springframework.stereotype.Component
@Component
class DateTimeToStringConverter : Converter<DateTime, String?> {
override fun convert(source: DateTime): String {
return source.format(Formatter.STANDARD_DATETIME)
}
}
@Component
class UUIDToStringConverter : Converter<UUID, String> {
override fun convert(source: UUID): String {
return source.getString()
}
}
@Component
class StringToDateTimeConverter : Converter<String, DateTime> {
override fun convert(source: String): DateTime {
return DateTime.parse(source, Formatter.STANDARD_DATETIME_MILLISECOUND7, true)
}
}
@Component
class StringToUUIDConverter : Converter<String, UUID> {
override fun convert(source: String): UUID {
return of(source)
}
}
@@ -16,14 +16,13 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile SystemUtil.kt
* LastUpdate 2025-09-14 21:56:58
* LastUpdate 2025-09-15 08:50:23
* UpdateUser MingLiPro
*/
@file:JvmName("SystemUtils")
package com.mingliqiye.utils.system
import com.mingliqiye.utils.collection.Lists
import java.net.Inet4Address
import java.net.NetworkInterface
import java.net.SocketException
@@ -90,14 +89,14 @@ fun getJavaVersionAsInteger(): Int {
"Invalid Java version format: $version"
)
}
version.substring(2, 3)
version[2] + ""
} else {
if (version.length < 2) {
throw IllegalStateException(
"Invalid Java version format: $version"
)
}
version.substring(0, 2)
version.take(2)
}
return uversion.toInt()
}
@@ -151,7 +150,7 @@ fun getLocalIps(): Array<String> {
* @return 本地IP地址的字符串列表
*/
fun getLocalIpsByList(): List<String> {
return Lists.newArrayList(*getLocalIps())
return getLocalIps().toList()
}
/**
@@ -179,7 +178,6 @@ fun getLoopbackIps(): Array<String> {
}
strings.toTypedArray()
} catch (e: SocketException) {
// 可考虑添加日志记录
arrayOf("127.0.0.1")
}
}
@@ -191,5 +189,5 @@ fun getLoopbackIps(): Array<String> {
*/
fun getLoopbackIpsByList(): List<String> {
// 将本地回环地址IP数组转换为列表并返回
return Lists.newArrayList(*getLoopbackIps())
return getLoopbackIps().toList()
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile UUID.kt
* LastUpdate 2025-09-14 19:55:47
* LastUpdate 2025-09-14 22:38:51
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.uuid
@@ -44,6 +44,9 @@ class UUID : Serializable {
return UUID(UuidCreator.getTimeBased())
}
@Deprecated("使用 getV1()", ReplaceWith("getV1()"), level = DeprecationLevel.WARNING)
fun getTimeBased(): UUID = getV1()
/**
* 获取 UUIDV4 版本的随机实例
* @return UUID