0
点赞
收藏
分享

微信扫一扫

properties总结

往复随安_5bb5 2022-01-26 阅读 43

properties总结

简介

路径:可以位于src目录下,也可以位于src的包下,使用时要注意路径问题

保存编码格式:UTF-8

命名规范:xxxx-config.properties

注释:# 注释

是一种key=value的配置文件

使用

db.properties

path:/springmvc/src/main/java/config/properties/db.properties

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/data?useUnicode=true&characterEncoding=utf8&useSSL=false
db.username=test
db.password=123456789

在java中获取

package com.util.constant.properties;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import java.util.ResourceBundle;

public class GetProperties {

	public static void main(String[] args) throws IOException {
		String absolutePath = "E:/center_final/springmvc/src/main/java/config/properties/db.properties";
		
		//方法一
		//路径:位于src下,文件名不能加后缀,前面不能加/
		//path:/springmvc/src/main/java/config/properties/db.properties
		ResourceBundle rb = ResourceBundle.getBundle("config/properties/db");
		System.out.println(rb.getString("db.username"));
		
		//方法二
		//路径:位于src下,文件名必须加后缀,前面必须加/
		InputStream is = GetProperties.class.getResourceAsStream("/config/properties/db.properties");
		Properties prop = new Properties();
		prop.load(is);
		System.out.println(prop.getProperty("db.driverClassName"));
		
		//方法三
		//路径:绝对路径,不推荐,文件名必须加后缀
		Properties properties = new Properties();
		BufferedReader br = new BufferedReader(new FileReader(absolutePath));
		properties.load(br);
		System.out.println(prop.getProperty("db.password"));
		
	}
	
	// 以下是对方法二和三的封装
	
	/**
	 * 根据name获取.properties文件里的value
	 * @param relativePath 文件的相对路径,相对于src
	 * @param name 待匹配的name
	 * @return
	 */
	public static String getValueByRelativePath(String relativePath, String key) {
		Properties properties = new Properties();
		try{
			// 利用反射获取对应的字段
			InputStream is = GetProperties.class.getClassLoader().getResourceAsStream(relativePath);
			                 // 类名.class.getClassLoader()
			properties.load(is);
		} catch(IOException e) {
			e.printStackTrace();
		}
		return properties.getProperty(key);
	}
	
	/**
	 * 根据name获取.properties文件里的value
	 * @param absolutePath 文件的绝对路径
	 * @param name 待匹配的name
	 * @return
	 */
	public static String getValueByAbsolutePath(String absolutePath, String key){
		Properties properties = new Properties();
		try{
			// 使用InPutStream流读取properties文件,可以是任意路径
			BufferedReader bufferedReader = new BufferedReader(new FileReader(absolutePath));
			properties.load(bufferedReader);
		} catch (IOException e){
			e.printStackTrace();
		}
		return properties.getProperty(key);
	}

}
举报

相关推荐

0 条评论