1.Servlet读取
<span style="font-family:KaiTi_GB2312;font-size:14px;">//ServletContext读取web应用中的资源文件
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
// 读取资源文件,最好采用ServletContext去读
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
this.getServletConfig().getServletContext();
//或是采用如下,通过ServletContext的getRealPath获取资源的绝对路径,在通过传统读取,这样可以获取资源名称
//String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
//String fileName = path.subString(path.lastIndexOf("\\")+1);//资源名称,这种方法会在下载时用到。
//FileInputStream in = new FileInputStream(path);
// 这里读取数据采用的是相对路径。
<span style="white-space:pre"> </span>// 这行代码是由服务器调用,所以此处的相对路径是C:\Program Files\Apache Software\Foundation\Tomcat 6.0\bin
// 需要在这个目录下建立classes/db.properties才能读取到
// InputStream in = new FileInputStream("classes/db.properties");
Properties props = new Properties();
props.load(in);// 继承自HashTable,但是这个方法是扩展的
System.out.println(props.getProperty("url"));
}</span>
2.普通类读取
<span style="font-family:KaiTi_GB2312;font-size:14px;">// 如果读取资源文件的程序不是Servlet的话,就只能通过类装载器去读,但要注意,读取的文件不能太大,否则,内存崩了
// 注意:这里是采用类装载器的方式,假如改了db.properties文件,那么读取时,类装器发现已经有了,就不读了。
// 当然这里采取的是静态代码块,更是只加载一次了
// 可以读取文件,但是无法读取更新后的
// private static Properties dbConfig = new Properties();
<span style="white-space:pre"> </span>// static{
<span style="white-space:pre"> </span>// try{
<span style="white-space:pre"> </span>// InputStream in =
// CommonWebSource.class.getClassLoader().getResourceAsStream("db.properties");
// dbConfig.load(in);
// }catch(Exception e){
// throw new ExceptionInInitializerError(e);
// }
// }
//这里只是通过类装载器拿出了路径(类似取出属性一样),并没有做任何装载操作,可以读到更新后的
public void update() throws IOException {
String path = CommonWebSource.class.getClassLoader().getResource("db.properties").getPath();
InputStream in = new FileInputStream(path);
Properties props = new Properties();
props.load(in);
System.out.println(props.getProperty("url"));
}</span>