This article has been checked for operation in the following environment.
C:\>java -version
openjdk version "11.0.3" 2019-04-16
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.3+7)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.3+7, mixed mode)
The following Main.java
reads the queen.properties
that exists on the classpath, and then formats and displays the contents.
Main.java
import java.io.IOException;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
try (var in = Main.class.getClassLoader().getResourceAsStream("queen.properties")) {
var properties = new Properties();
properties.load(in);
for (var key : properties.stringPropertyNames()) {
var value = properties.getProperty(key);
var message = String.format("key=`%s` value=`%s`", key, value);
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The contents of queen.properties
are as follows.
queen.properties
queen.vocal = Freddie Mercury
queen.guitar = Brian May
queen.bass = John Deacon
queen.drum = Roger Taylor
Well, I compiled Main.java
with javac
, generated Main.class
, and executed it as follows, but an error occurred and it did not behave as expected.
C:\>java -cp properties\queen.properties; Main
Exception in thread "main" java.lang.NullPointerException: inStream parameter is null
at java.base/java.util.Objects.requireNonNull(Objects.java:246)
at java.base/java.util.Properties.load(Properties.java:403)
at Main.main(Main.java:8)
__ In this case the intention was to add the queen.properties
stored in the properties
directory to the classpath. Therefore, I specified properties \ queen.properties
in the -cp
option that specifies the classpath, but it seems that it did not work well. __
Except when using wildcards (*
), it seems that the method of specifying the classpath is roughly as follows.
--Specify the file name for the jar file and zip file. --Other than that, specify the directory name.
The request was to specify the properties file as the classpath. Therefore, the latter is the correct answer for specifying the classpath. So, when I specified the directory name instead of the file name in the -cp
option, the behavior was as expected.
C:\>java -cp properties; Main
key=`queen.guitar` value=`Brian May`
key=`queen.drum` value=`Roger Taylor`
key=`queen.vocal` value=`Freddie Mercury`
key=`queen.bass` value=`John Deacon`
Recommended Posts