Java读取yml配置文件
时间: 2023-10-04 12:05:59 浏览: 129
Java中可以通过以下方式读取yml配置文件:
1. 引入相关依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.29</version>
</dependency>
```
2. 创建Yaml对象
```java
Yaml yaml = new Yaml();
```
3. 读取yml文件
```java
InputStream inputStream = new FileInputStream(new File("config.yml"));
Map<String, Object> map = yaml.load(inputStream);
```
以上代码将读取名为config.yml的yml文件,并将其转换为Map对象。
4. 获取配置信息
```java
String name = (String) map.get("name");
int age = (int) map.get("age");
List<String> hobbies = (List<String>) map.get("hobbies");
```
以上代码将从配置文件中获取name、age和hobbies配置信息。
完整代码示例:
```java
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
public class YmlReader {
public static void main(String[] args) throws Exception {
Yaml yaml = new Yaml();
InputStream inputStream = new FileInputStream(new File("config.yml"));
Map<String, Object> map = yaml.load(inputStream);
String name = (String) map.get("name");
int age = (int) map.get("age");
List<String> hobbies = (List<String>) map.get("hobbies");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Hobbies: " + hobbies);
}
}
```
阅读全文