how to create files under /WEB-INF/

故事扮演 提交于 2019-12-23 18:53:28

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/18530112/how-to-create-files-under-web-inf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!