Find the path of file in same directory during RUNTIME

751 views Asked by At

I have a struts2 and hibernate application. What I intend to do is that if database configuration is invalid, I recieve it from user and modify the hibernate.hbm.xml with updated settings. I am able to check and receive settings from user, only problem is that domparser cannot find my hibernate.cfg.xml.

String filepath = "hibernate.cfg.xml";
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(filepath);

When deploy the application as normal user, I get this

/home/uzumaki/hibernate.cfg.xml (No such file or directory)

and when I run as root,

/hibernate.cfg.xml (No such file or directory)

using File("").getAbsolutePath()) and concatinating with hibernate.cfg.xml also gives me same errors. The file is of course not there, it is in same folder as my java code/class, and goes everywhere with it (example war file)

1

There are 1 answers

2
Varun Garg On BEST ANSWER

After Searching a lot I finally found a way to get application's realpath during runtime. I am posting this in case anybody needs it.

HttpServletRequest servletRequest = ServletActionContext.getRequest();
String app_path;
app_path = servletRequest.getSession().getServletContext().getRealPath("/");

and now (In My Case)

String filepath =  app_path  + "WEB-INF/classes/hibernate.cfg.xml";