如何打开WEB-INF中的文件? [英] How do I open a file located in WEB-INF?
问题描述
我的servlet允许用户上传文件,我创建了一个按钮来查看上传的文件.
My servlet lets user upload a file, I've created a button to view the uploaded file.
现在,单击该按钮时,我希望打开上载的文件.如何在JSP端或servlet.java端做到这一点?
now, on click of that button I want the uploaded file to open. How do I do this on the JSP side or servlet.java side?
它位于WEB-INF/Uploads/my.txt文件夹中.
it is located in WEB-INF/Uploads/my.txt folder.
=====================================编辑========= ===============================
=====================================EDIT=========================================
根据下面的答案,我已经修改了代码,并将其粘贴到此处以获取更多答案,
Based on answers below, I've modified my code and I'm pasting the same here for more answers,
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ServletContext context = getServletContext();
String path = context.getRealPath("/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/Uploads/Config.txt");
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
String firstline = br.readLine();
System.out.println(firstline);
}
PS:这不起作用,仍在寻找答案. 谢谢!
PS: This is not working, still looking for answers. Thank You!
推荐答案
尝试执行以下操作:
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/WEB-INF/Uploads/my.txt");
然后阅读如下所示的URL内容:
then read the URL content like the following :
BufferedReader br = new BufferedReader(new InputStreamReader(
is));
int value=0;
// reads to the end of the stream
while((value = br.read()) != -1)
{
// converts int to character
char c = (char)value;
// prints character
System.out.println(c);
}
,请给我一些反馈
希望有帮助.
这篇关于如何打开WEB-INF中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!