Java如何读取yml文件呢?
下文笔者讲述java代码读取yml文件的方法及示例分享,如下所示
java读取yml文件的实现思路
Java读取YAML文件主要方式 ✅SnakeYAML: -轻量级,功能完整 -支持映射到Java对象 -适合简单项目 ✅Spring Boot: -自动配置,开箱即用 -强大的类型安全 -适合Spring项目 ✅最佳实践: -添加适当的错误处理 -使用try-with-resources管理资源 -验证YAML文件格式 -合理设计配置类结构
方式1:使用SnakeYAML库读取
添加依赖 <!-- Maven依赖 --> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>2.0</version> </dependency>
基础读取方式
import org.yaml.snakeyaml.Yaml; import java.io.FileInputStream; import java.io.InputStream; import java.util.Map; public class YamlReader { // 读取YAML文件为Map public static Map<String, Object> readYamlAsMap(String filePath) { try { InputStream inputStream = new FileInputStream(filePath); Yaml yaml = new Yaml(); return yaml.load(inputStream); } catch (Exception e) { e.printStackTrace(); return null; } } // 从classpath读取 public static Map<String, Object> readYamlFromClasspath(String fileName) { try { InputStream inputStream = YamlReader.class.getClassLoader() .getResourceAsStream(fileName); Yaml yaml = new Yaml(); return yaml.load(inputStream); } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { // 示例YAML内容: // server: // port: 8080 // host: localhost // database: // url: jdbc:mysql://localhost:3306/test // username: root // password: password Map<String, Object> yamlData = readYamlAsMap("config.yml"); if (yamlData != null) { System.out.println(yamlData); // 访问嵌套数据 Map<String, Object> server = (Map<String, Object>) yamlData.get("server"); System.out.println("Server Port: " + server.get("port")); System.out.println("Server Host: " + server.get("host")); } } }
2.映射到Java对象
定义配置类 // Server配置类 public class ServerConfig { private int port; private String host; private String contextPath; // 构造函数 public ServerConfig() {} // Getter和Setter public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } @Override public String toString() { return "ServerConfig{" + "port=" + port + ", host='" + host + '\'' + ", contextPath='" + contextPath + '\'' + '}'; } } //数据库配置类 public class DatabaseConfig { private String url; private String username; private String password; private int maxPoolSize; public DatabaseConfig() {} // Getter和Setter public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } @Override public String toString() { return "DatabaseConfig{" + "url='" + url + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", maxPoolSize=" + maxPoolSize + '}'; } } //主配置类 public class AppConfig { private ServerConfig server; private DatabaseConfig database; private list<String> profiles; public AppConfig() {} // Getter和Setter public ServerConfig getServer() { return server; } public void setServer(ServerConfig server) { this.server = server; } public DatabaseConfig getDatabase() { return database; } public void setDatabase(DatabaseConfig database) { this.database = database; } public List<String> getProfiles() { return profiles; } public void setProfiles(List<String> profiles) { this.profiles = profiles; } @Override public String toString() { return "AppConfig{" + "server=" + server + ", database=" + database + ", profiles=" + profiles + '}'; } } 读取并映射到对象 import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.InputStream; public class YamlToObjectMapper { //直接映射到对象 public static <T> T readYamlAsObject(String fileName, Class<T> clazz) { try { InputStream inputStream = YamlToObjectMapper.class.getClassLoader() .getResourceAsStream(fileName); Yaml yaml = new Yaml(new Constructor(clazz)); return yaml.load(inputStream); } catch (Exception e) { e.printStackTrace(); return null; } } //使用类型描述符 public static AppConfig readAppConfig(String fileName) { try { InputStream inputStream = YamlToObjectMapper.class.getClassLoader() .getResourceAsStream(fileName); Yaml yaml = new Yaml(); return yaml.loadAs(inputStream, AppConfig.class); } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { // 示例YAML文件内容 (application.yml): // server: // port: 8080 // host: localhost // context-path: /api // database: // url: jdbc:mysql://localhost:3306/test // username: root // password: password // max-pool-size: 20 // profiles: // - dev // - test AppConfig config = readAppConfig("application.yml"); if (config != null) { System.out.println(config); System.out.println("Server Port: " + config.getServer().getPort()); System.out.println("Database URL: " + config.getDatabase().getUrl()); System.out.println("Profiles: " + config.getProfiles()); } } }
3.使用Spring Boot(推荐)
添加Spring Boot依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>3.1.0</version> </dependency> 配置类定义 import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; @Component @ConfigurationProperties(prefix = "app") public class ApplicationProperties { private Server server = new Server(); private Database database = new Database(); private List<String> profiles; // Server内部类 public static class Server { private int port = 8080; private String host = "localhost"; private String contextPath = "/"; // Getter和Setter public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } } // Database内部类 public static class Database { private String url; private String username; private String password; private int maxPoolSize = 10; // Getter和Setter public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } } // 主类的Getter和Setter public Server getServer() { return server; } public void setServer(Server server) { this.server = server; } public Database getDatabase() { return database; } public void setDatabase(Database database) { this.database = database; } public List<String> getProfiles() { return profiles; } public void setProfiles(List<String> profiles) { this.profiles = profiles; } } 使用配置 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.commandlinerunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class YamlApplication implements CommandLineRunner { @Autowired private ApplicationProperties properties; public static void main(String[] args) { SpringApplication.run(YamlApplication.class, args); } @Override public void run(String... args) throws Exception { System.out.println("Server Port: " + properties.getServer().getPort()); System.out.println("Database URL: " + properties.getDatabase().getUrl()); System.out.println("Profiles: " + properties.getProfiles()); } } application.yml配置文件 app: server: port: 8080 host: localhost context-path: /api database: url: jdbc:mysql://localhost:3306/test username: root password: password max-pool-size: 20 profiles: - dev - test - prod
4.高级用法
处理复杂数据结构 import org.yaml.snakeyaml.Yaml; import java.util.; public class ComplexYamlReader { // 读取复杂YAML结构 public static void readComplexYaml() { String yamlContent = """ application: name: MyApp version: 1.0.0 environments: development: debug: true log-level: DEBUG databases: - name: primary url: jdbc:h2:mem:testdb pool-size: 5 - name: secondary url: jdbc:h2:mem:seconddb pool-size: 3 production: debug: false log-level: WARN databases: - name: primary url: jdbc:mysql://prod-server:3306/appdb pool-size: 20 """; Yaml yaml = new Yaml(); Map<String, Object> data = yaml.load(yamlContent); // 解析复杂结构 Map<String, Object> app = (Map<String, Object>) data.get("application"); System.out.println("Application Name: " + app.get("name")); Map<String, Object> environments = (Map<String, Object>) app.get("environments"); Map<String, Object> devEnv = (Map<String, Object>) environments.get("development"); System.out.println("Dev Debug: " + devEnv.get("debug")); List<Map<String, Object>> databases = (List<Map<String, Object>>) devEnv.get("databases"); for (Map<String, Object> db : databases) { System.out.println("DB Name: " + db.get("name")); System.out.println("DB URL: " + db.get("url")); } } }
YAML读取工具类简介
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import java.io.; import java.util.Map; public class YamlUtils { // 安全读取YAML文件 public static <T> T safeLoadYaml(String filePath, Class<T> clazz) { try (InputStream inputStream = new FileInputStream(filePath)) { Yaml yaml = new Yaml(new Constructor(clazz)); return yaml.load(inputStream); } catch (FileNotFoundException e) { System.err.println("YAML文件未找到: " + filePath); return null; } catch (Exception e) { System.err.println("解析YAML文件出错: " + e.getMessage()); return null; } } // 从classpath安全读取 public static <T> T safeLoadYamlFromClasspath(String fileName, Class<T> clazz) { try (InputStream inputStream = YamlUtils.class.getClassLoader() .getResourceAsStream(fileName)) { if (inputStream == null) { System.err.println("Classpath中未找到文件: " + fileName); return null; } Yaml yaml = new Yaml(new Constructor(clazz)); return yaml.load(inputStream); } catch (Exception e) { System.err.println("解析YAML文件出错: " + e.getMessage()); return null; } } // 验证YAML内容 public static boolean validateYaml(String filePath) { try (InputStream inputStream = new FileInputStream(filePath)) { Yaml yaml = new Yaml(); yaml.load(inputStream); return true; } catch (Exception e) { System.err.println("YAML文件验证失败: " + e.getMessage()); return false; } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。