使用反射来读取配置文件的两种方式:
//用来读取配置文件 @Test public void test2() throws Exception { Properties properties = new Properties(); //读取配置文件方式一 //这种方式只要路径正确都可以加载,没有要求 FileInputStream fileInputStream = new FileInputStream("src/main/java/com/example/demo/demo4/jdbc.properties"); properties.load(fileInputStream); //读取配置文件的方法二:使用ClassLoader //配置文件默认识别为:当前module的src下 // ClassLoader classLoader = ClassLoaderTest.class.getClassLoader(); // InputStream resourceAsStream = classLoader.getResourceAsStream("application.properties"); // properties.load(resourceAsStream); String user = properties.getProperty("user"); String password = properties.getProperty("password"); System.out.println("user = " + user + ",password = " + password); }如果配置文件中有中文,记得在setting中设置File Encodings,可以避免读取时乱码,如下图: