如何在/ WEB-INF /下创建文件

Neb*_*chi 3 servlets file web-inf

我正在开发一个存储/ WEB-INF/someFolder /下的文件的应用程序.但我找不到在此文件夹下创建文件的正确方法.我这样做了,但它不起作用:

        File newFile = new File("/WEB-INF/fileName.xml");
Run Code Online (Sandbox Code Playgroud)

当我尝试检查创建时:

        boolean isCreated = newFile.createNewFile();
Run Code Online (Sandbox Code Playgroud)

我明白了:

        java.io.IOException: No such file or directory
Run Code Online (Sandbox Code Playgroud)

请帮助我以正确的方式做到这一点.

更新: 我做了这个解决方法,它正在工作,但我没有看到它是高性能的解决方案.

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

有任何想法吗?

Uma*_*hta 7

您将使用ServletContext.getRealPath(String)并手动构建整个类路径

String webInfPath = getServletConfig().getServletContext().getRealPath("WEB-INF");
Run Code Online (Sandbox Code Playgroud)

或者一步一步走:

ServletConfig scfg= getServletConfig();
ServletContext scxt = scfg.getServletContext();
String webInfPath = sxct.getRealPath("WEB-INF");
Run Code Online (Sandbox Code Playgroud)

而且使用webInfPath在WEB-INF中创建一个File对象

File newFile = new File(webInfPath + "/fileName.xml");
Run Code Online (Sandbox Code Playgroud)

  • 从Tomcat 8开始,你应该使用`.getRealPath("/ WEB-INF")`否则你会得到空字符串.斜杠的起始路径与其他servlet容器兼容. (2认同)