一、非web程序读取资源文件
public class Test {
public static void main(String[] args) {
/**
* 方法一:当资源文件不常修改可用,当资源文件属性值改变时,由于是类加载器原理实现(对每个类只加载一次),
* 读取的数据不会改变,除非重启服务。
*/
InputStream in = Test.class.getClassLoader().getResourceAsStream("example.properties");
Properties p = new Properties();
try {
p.load(in);
System.out.println(p.getProperty("username") + "," + p.getProperty("password"));
} catch (IOException e) {
e.printStackTrace();
}
/**
* 方法二:当资源文件数据需要修改,而又不需重启服务,虽然用的还是类加载器原理,但是读取的是资源文件
* 的路径,资源数据采取io读取
*/
Properties p2 = new Properties();
String path = Test.class.getClassLoader().getResource("example.properties").getPath();
InputStream in2;
try {
in2 = new FileInputStream(new File(path));
p2.load(in2);
System.out.println(p.getProperty("username") + "," + p.getProperty("password"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/**
* 方法三:用工具类ResouceBundle,不过这个工具类通常用于国际化(根据Locale来指定特定资源文件)
*/
ResourceBundle rb = ResourceBundle.getBundle("example");
System.out.println(rb.getString("username") + "," + rb.getString("password"));
}
}
注意:用getClassLoader()方法,读取的资源文件不能太大(内存有限)。
二、web程序读取资源文件
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取ServletContext作用域对象
ServletContext st = this.getServletContext();
/**
* 文件位置不同的获取
*/
//位置一
InputStream in = st.getResourceAsStream("/WEB-INF/classes/first.properties");
//位置二
InputStream in2 = st.getResourceAsStream("/WEB-INF/classes/com/dx/servlet/second.properties");
//位置三
InputStream in3 = st.getResourceAsStream("/third.properties");
Properties p = new Properties();
p.load(in);
System.out.println(p.getProperty("username"));
p.load(in2);
System.out.println(p.getProperty("username"));
p.load(in3);
System.out.println(p.getProperty("username"));
//方式二(通过绝对路径来获取资源 可获取文件名)
String path = st.getRealPath("/WEB-INF/classes/first.properties");
String filename = path.substring(path.lastIndexOf("\\") + 1);
System.out.println("filename:" + filename);
InputStream in4 = new FileInputStream(new File(path));
p.load(in4);
System.out.println(p.getProperty("username"));
}