Config
Java properties file is normaly used to store project configuration data or settings.
/**
* Properties file to store project configuration data.
* Use getProperty() to get values.
*/
package com.minte9.collections.properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Config {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream(
"java-pages/src/main/java/com/minte9/" +
"collections/properties/" +
"config.properties"
);
Properties props = new Properties();
props.load(input);
String user = props.getProperty("db.user");
int port = Integer.parseInt(
props.getProperty("db.port")
);
System.out.println("user: " + user); // my_user
System.out.println("port: " + port); // 9000
}
}
/*
*/
List
Use list() or forEach() for quick parsing.
/**
* Use Enumeration to loop through a properties file.
* User forEach to access every property.
*/
package com.minte9.collections.properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class List {
public static void main(String[] args) throws IOException{
InputStream input = new FileInputStream(
"java-pages/src/main/java/com/minte9/" +
"collections/properties/" +
"config.properties"
);
Properties props = new Properties();
props.load(input);
props.list(System.out);
/*
-- listing properties --
db.user=my_user
db.pass=my_password
db.port=9000
db.url=localhost
*/
props.forEach((k, v) -> {
System.out.println(k + " : " + v);
});
/*
db.user : my_user
db.pass : my_password
db.port : 9000
db.url : localhost
*/
}
}
System
You can access many useful System properties.
/**
* Use list() to print all System properties.
*/
package com.minte9.collections.properties;
public class SystemProperties {
public static void main(String[] args) {
System.getProperties().list(System.out);
/*
...
os.name=Linux
java.vm.specification.version=11
sun.java.launcher=SUN_STANDARD
user.country=US
sun.boot.library.path=/usr/lib/jvm/java-11-openjdk-amd64/lib
....
*/
System.out.println(
System.getProperty("os.name") // Linux
);
}
}
Last update: 432 days ago