Skip to content

Instantly share code, notes, and snippets.

@P7h
Last active September 5, 2019 16:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save P7h/8635204 to your computer and use it in GitHub Desktop.
Save P7h/8635204 to your computer and use it in GitHub Desktop.
Load a properties file using Guava.
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();
}
}
}
}
}
@arganzheng
Copy link

with java 7+, you can simplify your code to:

public void loadProperties(String filename) {
    URL url = Resources.getResource(filename);

    final ByteSource byteSource = Resources.asByteSource(url);
    try (InputStream inputStream = byteSource.openBufferedStream()) {
        props.load(inputStream);
        props.list(System.out);
    } catch (IOException e) {
        LOGGER.error("openBufferedStream failed!", e);
    }
}

@agentgt
Copy link

agentgt commented Sep 5, 2019

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