Java 读取yaml文件 作者:马育民 • 2024-12-09 09:25 • 阅读:10004 # 说明 Java 读取yaml文件,有以下方法: - snakeyaml,springboot使用该库 - jackson,底层使用snakeyaml,使用 API 与 操作 JSON相同 本文讲解 snakeyaml 使用方法 # 添加依赖 ``` org.yaml snakeyaml 1.27 ``` # 例子1 读取 yaml 文件,并返回 `Map` ### yaml配置文件内容 在 `resources` 目录下创建 `application.yml` 配置文件,内容如下: ``` server: port: 8080 servlet: context-path: / spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver ``` ### 代码 ``` LoaderOptions options = new LoaderOptions(); options.setAllowDuplicateKeys(false); Yaml yaml = new Yaml(options); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream(path); Map map = yaml.load(inputStream); ``` # 例子2 将yaml文件解析成javabean ### 配置文件 ``` userId: 1 username: "lisi" password: '123456' address: province: 山东 city: "济南 : ss" hobbyList: - 游泳 - 跑步 ``` ### 代码 ``` import java.io.InputStream; import java.sql.Timestamp; import java.util.List; import java.util.Objects; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.yaml.snakeyaml.Yaml; public class Client { public static void main(String[] args) { InputStream resource = Client.class.getClassLoader().getResourceAsStream("User.yaml"); if (Objects.nonNull(resource)) { Yaml yaml = new Yaml(); User user = yaml.loadAs(resource, User.class); System.out.println(user.getClass()); System.out.println(user); } } @Setter @Getter @ToString @AllArgsConstructor @NoArgsConstructor public static class User { private String userId; private String username; private String password; private Timestamp createDate; private Address address; private List hobbyList; } @Setter @Getter @ToString @AllArgsConstructor @NoArgsConstructor public static class Address { private String province; private String city; } } ``` # 三条横线将一个文件分成多个配置 ### 配置文件 ``` userId: 1 username: "lisi" password: '123456' address: province: 山东 city: "济南 : ss" hobbyList: - 游泳 - 跑步 --- userId: 2 username: "lisi2" password: '123456' address: province: 河南 city: "郑州 : ss" hobbyList: - 下棋 - 画画 ... ``` - 在单一文件中,可用连续三个横线 `---` 区分多个文件。 - 还有选择性的连续三个点号 `...` 用来表示文件结尾。 ``` import org.yaml.snakeyaml.Yaml; import java.io.InputStream; import java.util.Objects; public class TestYaml { public static void main(String[] args) { InputStream resource = TestYaml.class.getClassLoader().getResourceAsStream("User.yaml"); if (Objects.nonNull(resource)) { Yaml yaml = new Yaml(); Iterable objects = yaml.loadAll(resource); for (Object object : objects) { System.out.println(object); } } } } ``` 参考: https://www.cnblogs.com/strongmore/p/14219180.html 原文出处:http://malaoshi.top/show_1GWBgo5e3Wj.html