|
| 1 | +package org.codefx.demo.java9.internal.resources; |
| 2 | + |
| 3 | +import java.io.FileInputStream; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStream; |
| 6 | +import java.util.Enumeration; |
| 7 | +import java.util.Properties; |
| 8 | +import java.util.PropertyResourceBundle; |
| 9 | +import java.util.stream.StreamSupport; |
| 10 | + |
| 11 | +public class ResourceFileEncoding { |
| 12 | + |
| 13 | + private static final String PATH_PREFIX = "out/"; |
| 14 | + |
| 15 | + public static void main(String[] args) { |
| 16 | + openFileAndPrint("config.properties", ResourceFileEncoding::printWithPropertyResourceBundle); |
| 17 | + openFileAndPrint("config.properties", ResourceFileEncoding::printWithProperties); |
| 18 | + } |
| 19 | + |
| 20 | + private static void openFileAndPrint(String propertyFileName, PrintProperties print) { |
| 21 | + try (InputStream propertyFile = new FileInputStream(PATH_PREFIX + propertyFileName)) { |
| 22 | + print.print(propertyFile); |
| 23 | + } catch (IOException e) { |
| 24 | + e.printStackTrace(); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + private static void printWithPropertyResourceBundle(InputStream propertyFile) throws IOException { |
| 29 | + System.out.println("\nWith `PropertyResourceBundle`..."); |
| 30 | + PropertyResourceBundle properties = new PropertyResourceBundle(propertyFile); |
| 31 | + properties.getKeys().asIterator().forEachRemaining(key -> { |
| 32 | + String value = properties.getString(key); |
| 33 | + System.out.println(key + " = " + value); |
| 34 | + }); |
| 35 | + } |
| 36 | + |
| 37 | + private static void printWithProperties(InputStream propertyFile) throws IOException { |
| 38 | + System.out.println("\nWith `Properties`..."); |
| 39 | + Properties properties = new Properties(); |
| 40 | + properties.load(propertyFile); |
| 41 | + properties.forEach((key, value) -> System.out.println(key + " = " + value)); |
| 42 | + } |
| 43 | + |
| 44 | + private interface PrintProperties { |
| 45 | + void print(InputStream propertyFile) throws IOException; |
| 46 | + } |
| 47 | + |
| 48 | +} |
0 commit comments