Last active
September 5, 2019 16:30
-
-
Save P7h/8635204 to your computer and use it in GitHub Desktop.
Load a properties file using Guava.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.URL; | |
import java.util.Properties; | |
import com.google.common.io.ByteSource; | |
import com.google.common.io.Resources; | |
/** | |
* Reads a properties file and print all the key value pairs to the console. | |
* Note: Writing to console is just for convenience here. | |
*/ | |
public final class ReadPropertiesWithGuava { | |
public final static void main(final String[] args) { | |
final URL url = Resources.getResource("spring-config.properties"); | |
final ByteSource byteSource = Resources.asByteSource(url); | |
final Properties properties = new Properties(); | |
InputStream inputStream = null; | |
try { | |
inputStream = byteSource.openBufferedStream(); | |
properties.load(inputStream); | |
properties.list(System.out); | |
} catch (final IOException ioException) { | |
ioException.printStackTrace(); | |
} finally { | |
if (inputStream != null) { | |
try { | |
inputStream.close(); | |
} catch (final IOException ioException) { | |
ioException.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
You can significantly improve the performance of loading Properties by making Properties write to something else instead of itself.
Properties properties = new Properties() {
final Map<String, String> ordered = new LinkedHashMap<String, String>();
// Hack to use properties class to load but our map for preserved order
@SuppressWarnings("serial")
Properties bp = new Properties() {
@Override
public Object put(
Object key,
Object value) {
return ordered.put((String) key, (String) value);
// return super.put(key, value);
}
};
}
The reason it is faster is because Properties is a HashTable which has all puts synchronized.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
with java 7+, you can simplify your code to: