java使用ClassLoader加载配置文件(properties)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

public class ClassLoaderTest {
    public static void main(String[] args) throws Exception {
        Properties pros = new Properties();
        // 此时的文件默认在当前工程下
        // 读取配置文件的方式一:
//        FileInputStream fis = new FileInputStream(new File("jdbc.properties"));
//        pros.load(fis);
        
        // 配置文件默认识别为:当前modules的src下
        // 读取配置文件的方式二:使用ClassLoader
        ClassLoader classLoader = ClassLoader.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("jdbc.properties");
        pros.load(is);
        
        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        System.out.println("user=" + user + " ,password=" + password);
    }
}

 

posted @ 2022-09-23 13:58  lai_xinghai  阅读(228)  评论(0)    收藏  举报