Java 读取 .yml 文件中的绝对路径配置
Java 读取 .yml 文件中的绝对路径配置
本文介绍如何在 Java 中使用 SnakeYAML 库读取 .yml 配置文件中的绝对路径配置,并提供完整的代码示例。
在 .yml 配置文件中配置绝对路径:
path:
absolute: '/path/to/my/file.txt'
在 Java 中调用该配置文件并读取绝对路径:
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
Yaml yaml = new Yaml();
try (InputStream in = Files.newInputStream(Paths.get('config.yml'))) {
Config config = yaml.loadAs(in, Config.class);
String filePath = config.getPath().getAbsolute();
System.out.println(filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Config {
private Path path;
public Path getPath() {
return path;
}
public void setPath(Path path) {
this.path = path;
}
}
class Path {
private String absolute;
public String getAbsolute() {
return absolute;
}
public void setAbsolute(String absolute) {
this.absolute = absolute;
}
}
代码说明:
- 使用
org.yaml.snakeyaml.Yaml库读取配置文件。 - 使用
Files.newInputStream(Paths.get('config.yml'))获取配置文件的输入流。 - 使用
yaml.loadAs(in, Config.class)将配置文件内容映射到Config对象。 - 通过
config.getPath().getAbsolute()获取配置文件中的绝对路径。
注意:
- 确保你的项目中已经添加了 SnakeYAML 库的依赖。
- 替换
config.yml为你的配置文件名。 - 替换
/path/to/my/file.txt为你的实际绝对路径。
通过以上步骤,你就可以在 Java 中轻松地读取 .yml 文件中的绝对路径配置。
原文地址: https://www.cveoy.top/t/topic/n6sl 著作权归作者所有。请勿转载和采集!