logo

Java - Environment and Properties

Last Updated: 2022-08-06

JAVA_HOME

  • tools: $JAVA_HOME/bin, including javac, jshell, jlink, etc
  • run-time image file: $JAVA_HOME/lib/modules

CLASSPATH

  • CLASSPATH cannot be a folder, need to include each jar /path/to/*.jar
  • use the first match

System Environment

Environment settings in ~/.bashrc or ~/.bash_profile, which can be checked in linux cmd env

$ env
JAVA_HOME=...
SHELL=/bin/sh
...

are available in Java by System.getenv():

jshell> System.getenv().entrySet().stream().map(x->x.getKey()).collect(Collectors.toList());
$1 ==> [PATH, LESSCLOSE, LESSOPEN, SHELL, JAVA_HOME, HOSTTYPE, TERM, USER, LANG, NAME, WSLENV, LOGNAME, WS, PWD, LS_COLORS, HOME, SHLVL, _]

System Properties

System.getenv() is more about the underlying operating system, while System.getProperties() is more about the Java/JVM environment:

jshell> System.getProperties().entrySet().stream().map(x->x.getKey()).collect(Collectors.toList());
$2 ==> [awt.toolkit, java.specification.version, sun.cpu.isalist, sun.jnu.encoding, java.class.path, java.vm.vendor, sun.arch.data.model, java.vendor.url, user.timezone, os.name, java.vm.specification.version, sun.java.launcher, user.country, sun.boot.library.path, sun.java.command, jdk.debug, sun.cpu.endian, user.home, user.language, java.specification.vendor, java.version.date, java.home, file.separator, java.vm.compressedOopsMode, line.separator, java.specification.name, java.vm.specification.vendor, java.awt.graphicsenv, sun.management.compiler, java.runtime.version, user.name, path.separator, os.version, java.runtime.name, file.encoding, java.vm.name, java.vendor.version, java.vendor.url.bug, java.io.tmpdir, java.version, user.dir, os.arch, java.vm.specification.name, java.awt.printerjob, sun.os.patch.level, java.library.path, java.vendor, java.vm.info, java.vm.version, sun.io.unicode.encoding, java.class.version]

You can also set properties in command-line by -D<name>=<value>, e.g.

$ java ... -Dmy.property=aloha

Properties

Properties is serializable, often used to store configurations/settings.

Create a new(void) Properties

import java.util.Properties;
Properties props = new Properties();

Load properties from file

try (FileInputStream fis = new FileInputStream("path/to/propFile")) {
    props.load(fis);
} catch (IOException e) {
    System.out.println("Can not open property file: " + propFile);
}

The propFile may look like this

# Comments
key:value

# Comments
key:value

Get a property by name

props.getProperty("input_paths");