当前位置: 代码迷 >> 综合 >> web应用中普通java程序读取资源文件
  详细解决方案

web应用中普通java程序读取资源文件

热度:44   发布时间:2023-10-25 13:46:48.0
普通java程序读取资源文件(Servlet调用其它程序进而读取资源,通过类装载器)文件不能太大
注意,类只装载一次所以改没改没有什么乱用
package hyl;


import hyl.dao.UserDao;


import java.io.IOException;


import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ServletDemo1 extends HttpServlet {



public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();

UserDao dao = new UserDao();
dao.update();
}



public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


doGet(request,response);
}


}




package hyl.dao;


import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;




public class UserDao {

public void update() throws IOException{
InputStream in = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(in);

System.out.println("url");
}
}
为了实现代码的共用我们可以使用代码块来实现
package hyl.dao;


import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;




public class UserDao {
private static Properties dbconfig = new Properties();
static{
try{InputStream in = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(in);}catch(Exception e){
throw new ExceptionInInitializerError(e);
}
System.out.println("url");
}
public void update() throws IOException{
System.out.println(dbconfig.getProperty("url"));
}
}




//注意,类只装载一次所以改没改(资源文件中的内容)没有什么乱用,要想克服这一点的话我们就需要避免类装载器,但是呢我们可以通过类装载来得到path我们需要的是path
UserDao.class.getClassLoader().getResource("db.properties").getPath();
//然后通过流的传统方式来获取资源