how to create files under /WEB-INF/

Jason Bourne picture Jason Bourne · Aug 30, 2013 · Viewed 13.6k times · Source

I am working on an application that stores files under /WEB-INF/someFolder/. But I dont find the right way to create files under this folder. I did this, but it is not working:

        File newFile = new File("/WEB-INF/fileName.xml");

When I try to check the creation:

        boolean isCreated = newFile.createNewFile();

I get :

        java.io.IOException: No such file or directory

Please help me doing it in the right way.

Update: I did this workaround, it is working but I dont see that it is performant solution.

        ServletContext servletContext = getServletContext();
        String path = servletContext.getRealPath("/WEB-INF/");
        File newFile2 = new File(path+"/fileName.xml");

Any ideas?

Answer

Umang Mehta picture Umang Mehta · Aug 30, 2013

You shall use ServletContext.getRealPath(String) and build the entire classpath manually

String webInfPath = getServletConfig().getServletContext().getRealPath("WEB-INF");

OR go step by step:

ServletConfig scfg= getServletConfig();
ServletContext scxt = scfg.getServletContext();
String webInfPath = sxct.getRealPath("WEB-INF");

And than use the webInfPath to create a File object inside WEB-INF

File newFile = new File(webInfPath + "/fileName.xml");