您好,我必须使用 java 动态在项目中创建一个 XML 文件,并且必须使用基本路径 URL 读取它。我可以在手动创建文件时读取该文件,但无法动态创建它。当我使用 File f1 = new File("test.XML"); 时,它会在 tomcat 的 Bin 文件夹中创建文件。在 Tomcat 和 Jboss EAP 6 中运行时,必须在项目中创建该文件。
最佳答案
您可以使用 servlet 上下文获取 Web 应用程序的真实路径:
new File( servletContext.getRealPath( "/text.XML" ) );
注意:如果您在 Linux 上运行 tomcat/jboss,您可能必须授予在 webapp 文件夹中写入的权限,而默认情况下这很可能是被禁止的。
引用ServletContext.getRealPath()
的Servlet API文档:
Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns the absolute file path on the server's filesystem would be served by a request for "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext..
关于java - 如何在java web项目运行时在webroot中创建文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12747715/