Java 从 servlet 访问 WebContent 文件夹中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1479036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access file in WebContent folder from a servlet
提问by jobinbasani
I'm trying to generate a PDF document using FOP. The pdf generation code is kept in a servlet and the xsl is in a specific folder in the WebContent folder.
我正在尝试使用 FOP 生成 PDF 文档。pdf 生成代码保存在 servlet 中,xsl 位于 WebContent 文件夹中的特定文件夹中。
How can I access this xsl file by giving a relative path? It works only if I give the complete path in the File object.
如何通过提供相对路径来访问此 xsl 文件?仅当我在 File 对象中提供完整路径时才有效。
I need to generate the xml content dynamically. How can I give this dynamically generated xml as the source instead of a File object?
我需要动态生成 xml 内容。如何将这个动态生成的 xml 作为源而不是 File 对象?
Please provide your suggestions.
请提供您的建议。
采纳答案by GBa
To get the path you can just do:
要获得路径,您可以执行以下操作:
String path = s.getServletContext().getRealPath("/WEB-INF/somedir/hdfeeh");
s
is the class that implements HTTPServlet
.You can also use this.getServletContext()
if its your servlet class.
s
是实现 的类。如果它是您的 servlet 类,HTTPServlet
您也可以使用this.getServletContext()
。
Then pass this as a parameter.
然后将其作为参数传递。
As far as using dynamically generated XML, the library you're using should support using an input stream, write your XML, convert it to a byte array, then wrap it in a ByteArrayInputStream
and use this.
至于使用动态生成的 XML,您使用的库应该支持使用输入流,编写您的 XML,将其转换为字节数组,然后将其包装在 a 中ByteArrayInputStream
并使用它。
回答by Andre Pastore
For a direct and independent container implementation, you can access the resourcewith the following method getResource() inside your servlet:
对于直接和独立的容器实现,您可以在 servlet 中使用以下方法 getResource() 访问资源:
/start servlet/
/启动小服务程序/
public InputStream getResource(String resourcePath) {
ServletContext servletContext = getServletContext();
InputStream openStream = servletContext.getResourceAsStream( resourcePath );
return openStream;
}
public void testConsume() {
String path = "WEB-INF/teste.log";
InputStream openStream = getResource( path );
int c = -1;
byte[] bb = new byte[1024];
while ( -1 != ( c = openStream.read( bb ) ) ) {
/* consume stream */
}
openStream.close();
}
/end servlet/
/结束小服务程序/
回答by Rajan
I used the following method to read the file under web content
我用下面的方法来读取网页内容下的文件
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getSession().getServletContext().getResourceAsStream("/json/sampleJson.json")));
Now all the file content is available in the reader object.
现在所有文件内容都可以在 reader 对象中使用。