两种方式读取maven工程的properties配置文件
一、新建maven工程,并在resource文件夹下建立需要读取的配置文件(若新建的maven工程没有resource文件夹,则自己新建),例如systemConfig.properties
二、读取配置文件
1.通过ResourceBundle类读取
import java.util.ResourceBundle; public class ResourceUtil { private static final ResourceBundle resourceBundle; static{ resourceBundle = ResourceBundle.getBundle("systemConfig"); } public static String getKey(String key){ return resourceBundle.getString(key); } }
2.通过properties读取
public class PropertiesTest { public static Properties confProperties; static { try { init(); } catch (Exception e) { e.printStackTrace(); } } public static void init() throws IOException { if (confProperties == null) { confProperties = new Properties(); InputStream in = PropertiesTest.class.getClassLoader().getResourceAsStream("systemConfig.properties"); try { confProperties.load(in); } catch (IOException e) { e.printStackTrace(); } finally { in.close(); } } } public static Properties getProperties() throws IOException { init(); return confProperties; } public static void clear() { confProperties.clear(); confProperties = null; } public static String get(String key) { try { init(); } catch (IOException e) { e.printStackTrace(); } return confProperties.getProperty(key); } }
注意:因为必须将项目跑起来才能读取properties,因此不能直接通过main方法测试
三、测试
因此我写了一个Controller