how to create files under /WEB-INF/

14.4k views Asked by At

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?

2

There are 2 answers

0
toby941 On BEST ANSWER

make sure you applaction have the permissions to write. you can get the path ues like this:

String path=Thread.currentThread().getContextClassLoader().getResource("com/youpackage/");

Now you get the path which is your class folder path,so you can get the WEB-INF path. ps: i remember when create file you must writer some content,otherwies it may not create.

1
Umang Mehta On

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");