我的Java程序应该连接到另外两台机器(已知IP地址和端口)并执行数据比较任务。
我没有硬编码Java源文件中的IP和端口,而是创建了一个config.yaml
文件并将其存储如下,让我们说这是该文件的上下文:
config.yaml:
other machines:
-"firstMachineAddress:162.242.195.82"
-"secondMachineAddress:50.31.209.229"
-"firstTargetPort:4041"
-"secondTargetPort:4042"
现在我想在我的Java源文件中加载这些值并将它们分配给我已创建的变量,例如:
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 = "";
我想知道Java是否提供了实现此目的的便捷方式?
答案 0 :(得分:2)
https://github.com/FasterXML/jackson-dataformat-yaml
复制下面的粘贴
要在基于Maven的项目上使用此扩展,请使用以下依赖项:
<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>
用法与基本JsonFactory
一样;最常见的是,您只需使用ObjectMapper
构建标准com.fasterxml.jackson.dataformat.yaml.YAMLFactory
,如下所示:
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
User user = mapper.readValue(yamlSource, User.class);
但您也可以使用它生成的基础YAMLFactory
和解析器,用于基于事件的处理:
YAMLFactory factory = new YAMLFactory();
JsonParser parser = factory.createJsonParser(yamlString); // don't be fooled by method name...
while (parser.nextToken() != null) {
// do something!
}