假设在SRC根目录下有文件 config.properties ,下面代码就是读取这个文件的例子程序
方法1
补充说明:要获取某包下的配置文件可以通过某类获取同一级包下的文件,具体为
方法2
写某包下的Properties文件
方法1
Properties prop = new Properties();
InputStream in = Object.class.getResourceAsStream("/config.properties");
prop.load(in);
String databasePath = prop.getProperty("DATA_SOURCE").trim();
补充说明:要获取某包下的配置文件可以通过某类获取同一级包下的文件,具体为
//Object 就是指定的类,下面的方法会去指定类的包下找叫config.properties的配置文件
InputStream in = Object.class.getResourceAsStream("config.properties");
方法2
String fp = this.getClass().getClassLoader().getResource("/").getPath() + "config.properties";
File file = new File(fp);
Properties properties = new Properties();
properties.load(new FileInputStream(file));
String urlfilter = properties.getProperty("DATA_SOURCE");
写某包下的Properties文件
//MyObject是项目里面的类
String fp = MyObject.getClass().getClassLoader().getResource("/cn/myproject/").getPath() + "config.properties";
File file = new File(fp);
Properties properties = new Properties();
properties.load(new FileInputStream(file));
String urlfilter = properties.getProperty("DATA_SOURCE");