name.remal.java.util.Properties.kt Maven / Gradle / Ivy
package name.remal
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
import java.io.File
import java.io.InputStream
import java.io.Reader
import java.io.StringReader
import java.io.StringWriter
import java.util.Properties
import kotlin.text.Charsets.UTF_8
@Deprecated("Use string keys and values")
@SuppressFBWarnings("NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", "IPU_IMPROPER_PROPERTIES_USE_SETPROPERTY")
operator fun Properties.set(key: Any?, value: Any?) = put(key, value)
operator fun Properties.set(key: String, value: String?): String? {
if (value == null) {
val prevValue = getProperty(key)
remove(key)
return prevValue
} else {
val prevValue = getProperty(key)
setProperty(key, value)
return prevValue
}
}
fun loadProperties(file: File) = Properties().apply { load(file) }
fun loadProperties(content: String) = Properties().apply { load(content) }
fun loadProperties(content: InputStream) = Properties().apply { load(content) }
fun loadProperties(content: Reader) = Properties().apply { load(content) }
fun Properties.load(file: File) {
file.toPath().newInputStream().use { load(it) }
}
fun Properties.load(content: String) {
StringReader(content).use { load(it) }
}
fun Properties.storeAsString(doStripComments: Boolean = true): String {
var content = StringWriter().use { store(it, ""); it.toString() }
if (doStripComments) {
content = content.splitToSequence('\n')
.map { it.substringBefore('#').trim() }
.filter(String::isNotEmpty)
.joinToString("\n")
}
return content
}
fun Properties.store(file: File, doStripComments: Boolean = true) {
file.createParentDirectories().writeText(storeAsString(doStripComments), UTF_8)
}