一尘不染

如何打开WEB-INF中的文件?

jsp

我的servlet允许用户上传文件,我创建了一个按钮来查看上传的文件。

现在,单击该按钮,我希望打开上载的文件。如何在JSP端或servlet.java端执行此操作?

它位于WEB-INF / Uploads / my.txt文件夹中。

=====================================编辑=============

根据下面的答案,我已经修改了代码,并在此处粘贴了相同的代码以获取更多答案,

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:这不起作用,仍在寻找答案。谢谢!


阅读 278

收藏
2020-06-10

共1个答案

一尘不染

尝试执行以下操作:

ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/WEB-INF/Uploads/my.txt");

然后读取网址内容,如下所示:

  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);
         }

请给我一些反馈

希望有帮助。

2020-06-10