|
20 | 20 | import io.microsphere.annotation.Nonnull; |
21 | 21 | import io.microsphere.util.Utils; |
22 | 22 |
|
| 23 | +import java.io.StringReader; |
23 | 24 | import java.util.LinkedHashMap; |
24 | 25 | import java.util.Map; |
25 | 26 | import java.util.Properties; |
26 | 27 |
|
27 | 28 | import static io.microsphere.collection.MapUtils.isEmpty; |
28 | 29 | import static io.microsphere.collection.MapUtils.newLinkedHashMap; |
| 30 | +import static io.microsphere.constants.SeparatorConstants.FILE_SEPARATOR; |
| 31 | +import static io.microsphere.constants.SeparatorConstants.LINE_SEPARATOR; |
29 | 32 | import static io.microsphere.constants.SymbolConstants.DOT; |
| 33 | +import static io.microsphere.lang.function.ThrowableAction.execute; |
| 34 | +import static io.microsphere.util.ArrayUtils.length; |
| 35 | +import static io.microsphere.util.StringUtils.arrayToString; |
30 | 36 | import static java.util.Collections.unmodifiableMap; |
31 | 37 |
|
32 | 38 | /** |
@@ -144,6 +150,45 @@ public static Properties newProperties(Properties defaults) { |
144 | 150 | return new Properties(defaults); |
145 | 151 | } |
146 | 152 |
|
| 153 | + /** |
| 154 | + * Loads properties from the given string values. |
| 155 | + * |
| 156 | + * <p>The provided string values are joined using the system file separator to form a single content string, |
| 157 | + * which is then parsed as a standard Java properties format.</p> |
| 158 | + * |
| 159 | + * <h3>Example Usage</h3> |
| 160 | + * <pre>{@code |
| 161 | + * // Load properties from multiple lines |
| 162 | + * Properties props = PropertiesUtils.loadProperties( |
| 163 | + * "key1=value1", |
| 164 | + * "key2=value2" |
| 165 | + * ); |
| 166 | + * System.out.println(props.getProperty("key1")); // Output: value1 |
| 167 | + * System.out.println(props.getProperty("key2")); // Output: value2 |
| 168 | + * |
| 169 | + * // Load empty properties if no arguments are provided |
| 170 | + * Properties emptyProps = PropertiesUtils.loadProperties(); |
| 171 | + * System.out.println(emptyProps.isEmpty()); // Output: true |
| 172 | + * }</pre> |
| 173 | + * |
| 174 | + * @param propertiesValue the string values representing properties content |
| 175 | + * @return a new {@link Properties} instance loaded from the given values |
| 176 | + */ |
| 177 | + @Nonnull |
| 178 | + public static Properties loadProperties(String... propertiesValue) { |
| 179 | + int length = length(propertiesValue); |
| 180 | + Properties properties = newProperties(); |
| 181 | + if (length > 0) { |
| 182 | + String content = arrayToString(propertiesValue, LINE_SEPARATOR); |
| 183 | + execute(() -> { |
| 184 | + try (StringReader reader = new StringReader(content)) { |
| 185 | + properties.load(reader); |
| 186 | + } |
| 187 | + }); |
| 188 | + } |
| 189 | + return properties; |
| 190 | + } |
| 191 | + |
147 | 192 | private PropertiesUtils() { |
148 | 193 | } |
149 | 194 | } |
0 commit comments