Add ClassLoader.asResourceContainer; Fix nullability of getResource

This commit is contained in:
Him188 2020-08-20 12:52:19 +08:00
parent 8dd692bbb5
commit a478b85ba2

View File

@ -22,26 +22,26 @@ import kotlin.reflect.KClass
*
* 资源容器可能使用 [Class.getResourceAsStream], 也可能使用其他方式, 取决于实现方式.
*
* @see JvmPlugin [JvmPlugin] 实现 [ResourceContainer], 使用 [ResourceContainer.asResourceContainer]
* @see JvmPlugin [JvmPlugin] 通过 [ClassLoader.getResourceAsStream] 实现 [ResourceContainer], 使用 [ResourceContainer.asResourceContainer]
*/
public interface ResourceContainer {
/**
* 获取一个资源文件
*/
public fun getResourceAsStream(name: String): InputStream
public fun getResourceAsStream(name: String): InputStream?
/**
* 读取一个资源文件并以 [Charsets.UTF_8] 编码为 [String]
*/
@JvmDefault
public fun getResource(name: String): String = getResource(name, Charsets.UTF_8)
public fun getResource(name: String): String? = getResource(name, Charsets.UTF_8)
/**
* 读取一个资源文件并以 [charset] 编码为 [String]
*/
@JvmDefault
public fun getResource(name: String, charset: Charset): String =
String(this.getResourceAsStream(name).use { it.readBytes() })
public fun getResource(name: String, charset: Charset): String? =
this.getResourceAsStream(name)?.use(InputStream::readBytes)?.let(::String)
public companion object {
/**
@ -51,6 +51,13 @@ public interface ResourceContainer {
@JvmName("create")
public fun KClass<*>.asResourceContainer(): ResourceContainer = this.java.asResourceContainer()
/**
* 使用 [Class.getResourceAsStream] 读取资源文件
*/
@JvmStatic
@JvmName("create")
public fun ClassLoader.asResourceContainer(): ResourceContainer = ClassLoaderAsResourceContainer(this)
/**
* 使用 [Class.getResourceAsStream] 读取资源文件
*/
@ -63,5 +70,11 @@ public interface ResourceContainer {
private class ClassAsResourceContainer(
private val clazz: Class<*>
) : ResourceContainer {
override fun getResourceAsStream(name: String): InputStream = clazz.getResourceAsStream(name)
override fun getResourceAsStream(name: String): InputStream? = clazz.getResourceAsStream(name)
}
private class ClassLoaderAsResourceContainer(
private val clazz: ClassLoader
) : ResourceContainer {
override fun getResourceAsStream(name: String): InputStream? = clazz.getResourceAsStream(name)
}