Reputation: 1084
I've a Java program that should connect to two other machines (IP addresses and ports are known) and do a data comparison task.
Instead of hardcoding the IP and port in the Java source file, I created a config.yaml
file and stored these there as follows, let's say this is the context of that file:
config.yaml:
other machines:
-"firstMachineAddress:162.242.195.82"
-"secondMachineAddress:50.31.209.229"
-"firstTargetPort:4041"
-"secondTargetPort:4042"
Now I want to load these values in my Java source file and assign them to the variables I created already, such as:
sampleClass.java:
// addresses of the machines which we will connect
public final InetAddress firstMachineAddress = "";
public final InetAddress secondMachineAddress = "";
private final int firstTargetPort = "";
private final int secondTargetPort = "";
I was wondering if Java provides a convenient way to achieve this?
Upvotes: 1
Views: 8458
Reputation: 2845
https://github.com/FasterXML/jackson-dataformat-yaml
Copy paste below
To use this extension on Maven-based projects, use the following dependencies:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
Usage is as with basic JsonFactory
; most commonly you will just construct a standard ObjectMapper
with com.fasterxml.jackson.dataformat.yaml.YAMLFactory
, like so:
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
User user = mapper.readValue(yamlSource, User.class);
but you can also just use underlying YAMLFactory
and parser it produces, for event-based processing:
YAMLFactory factory = new YAMLFactory();
JsonParser parser = factory.createJsonParser(yamlString); // don't be fooled by method name...
while (parser.nextToken() != null) {
// do something!
}
Upvotes: 2