【问题标题】:how to create files under /WEB-INF/如何在 /WEB-INF/ 下创建文件
【发布时间】:2013-09-03 00:26:19
【问题描述】:

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

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

当我尝试检查创建时:

        boolean isCreated = newFile.createNewFile();

我明白了:

        java.io.IOException: No such file or directory

请帮助我以正确的方式进行操作。

更新: 我做了这个解决方法,它正在工作,但我不认为它是高性能的解决方案。

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

有什么想法吗?

【问题讨论】:

    标签: file servlets web-inf


    【解决方案1】:

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

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

    或者一步一步来:

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

    然后使用 webInfPath 在 WEB-INF 中创建一个 File 对象

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

    【讨论】:

    • 从 Tomcat 8 开始,你应该使用 .getRealPath("/WEB-INF") 否则你会得到空字符串。带斜线的起始路径与其他 servlet 容器兼容。
    【解决方案2】:

    确保您的应用程序具有写入权限。 你可以像这样得到路径:

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

    现在你得到了你的类文件夹路径,所以你可以得到WEB-INF路径。 ps:我记得创建文件的时候一定要写一些内容,否则可能无法创建。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多