依赖包
< dependency>
< groupId> org.yaml</ groupId>
< artifactId> snakeyaml</ artifactId>
< version> 1.30</ version>
</ dependency>
工具类封装
package com. demo. utils ;
import org. springframework. util. CollectionUtils ;
import org. yaml. snakeyaml. Yaml ;
import java. io. File ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ;
import java. io. InputStream ;
import java. util. Map ;
import java. util. Stack ;
import java. util. concurrent. ConcurrentHashMap ;
import java. util. stream. Collectors ;
public class YamlUtil {
public static void main ( String [ ] args) throws FileNotFoundException {
String path = "C:\\Users\\Administrator\\Desktop\\yml\\application.yml" ;
File file = new File ( path) ;
Map < String , Object > map = null ;
if ( file. exists ( ) ) {
InputStream inputStream = new FileInputStream ( file) ;
Yaml yaml = new Yaml ( ) ;
map = yaml. load ( inputStream) ;
}
Map < String , Object > yml = new ConcurrentHashMap < > ( 16 ) ;
if ( ! CollectionUtils . isEmpty ( map) ) {
getVal ( new Stack < > ( ) , map, yml) ;
}
yml. forEach ( ( k, v) -> {
System . out. println ( k + ":" + v) ;
} ) ;
}
public static void getVal ( Stack < String > stack, Map < String , Object > map, Map < String , Object > yml) {
for ( String key: map. keySet ( ) ) {
Object tmp = map. get ( key) ;
stack. add ( key) ;
if ( tmp instanceof Map ) {
getVal ( stack, ( Map < String , Object > ) tmp, yml) ;
} else {
yml. put ( stack. stream ( ) . collect ( Collectors . joining ( "." ) ) , tmp) ;
stack. pop ( ) ;
}
}
if ( ! stack. isEmpty ( ) ) {
stack. pop ( ) ;
}
}
}
测试用YML文件
spring :
profiles :
active : 1
dev : 2
https :
timeout : 3000
netty : 4
server :
port : 8078
测试结果
Connected to the target VM, address : '127.0.0.1:63707' , transport : 'socket'
Java HotSpot ( TM) 64-Bit Server VM warning : Sharing is only supported for boot loader classes because bootstrap classpath has been appended
spring.netty : 4
spring.profiles.dev : 2
spring.profiles.active : 1
server.port : 8078
spring.profiles.https.timeout : 3000
Disconnected from the target VM, address : '127.0.0.1:63707' , transport : 'socket'
Process finished with exit code 0