基础学习-Properties类、Class类getResource方法

一、Properties

Properties类是什么? Properties(Java.util.Properties),该类主要用于读取Java的配置文件,Java中,其配置文件常为.properties文件,是以键值对的形式进行参数配置的。

文件格式: 键=值 键=值

常见方法:

load:加载配置文件的键值对到Properties对象 list:将数据显示到指定设备 getProperties(key):根据键获取值 setProperties(key,value):设置键值对到Properties对象,如果key不存在,新建;如果存在,修改 store:将Properties中的键值对存储到配置文件,如果含有中文,会存储问Unicode码
例:jdbc-config.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/oa
username=root
password=123456
//        获取properties对象
       Properties properties = new Properties();
//        通过当前类的类加载器,将class字节码文件加载进内存
        //执行该代码后,默认以src为根路径
        ClassLoader classLoader=TestDemo.class.getClassLoader();
//        通过getResource方法加载指定文件资源
        URL resource = classLoader.getResource("jdbc-config.properties");
//        通过getPath方法获取绝对路径,返回对应的String类型对象
        String path = resource.getPath();
//       URLDecoder类中的decode方法用于将路径中的特殊字符转换为普通字符串
        URLDecoder urlDecoder = new URLDecoder();
        String decode = urlDecoder.decode(path, "UTF-8");
//       读取指定文件        
        FileInputStream fileInputStream = new FileInputStream(path);
        properties.load(fileInputStream);
        fileInputStream.close();
//        控制台输出结果:com.mysql.cj.jdbc.Driver------jdbc:mysql://localhost:3306/oa
        System.out.println(properties.getProperty("driver")+"------"+properties.getProperty("url"));

二、Class类中getResource方法使用

getResource方法是得到文件路径的函数。 idea默认扫描src包下resources资源目录

1、得到src下的a.properties的路径。
String value=TestMain2.class.getResource("/a.properties").toString();

2 如果该方法参数中以“/”开头表示的是src根目录下开始查找。如果不是以“/”开头的则表示从当前类的包中开始查找。
String value=TestMain2.class.getResource("/a.properties").toString();
--从src下开始查找
String value=Test.class.getResource("aaa.xml").toString();
--从当前类所在的包开始查找

3 通过“类名.class.getResource(String string)”即可。用类名
如:String value=TestMain2.class.getResource("/a.properties").toString();

4 如果想要查找当前工程所在的目录,则参数为:“/”即可。
如:String value=Test.class.getResource("/").toString();

5 如果想要查找当前类所在的目录。则参数为:""即可。为空字符串即可。
如:String value=Test.class.getResource("").toString();

如果路径目录存在特殊字符(空格...),则使用URLDecoder类进行转换
URLDecoder类中的decode方法用于将特殊字符转换为普通字符串
例D:java
ew style
dataFile = XmlDataSource.class.getResource("/painting.xml").getPath();
URLDecoder decoder=new URLDecoder();
decoder.decode(dataFile,"UTF-8");
经验分享 程序员 微信小程序 职场和发展