【问题标题】:How do I write to a file from a servlet-filter and read it in Eclipse?如何从 servlet-filter 写入文件并在 Eclipse 中读取它?
【发布时间】:2011-12-09 14:05:58
【问题描述】:

我想从我的过滤器写入一个文件,然后能够在 Eclipse 中读取它以确保我已正确写入。

这段代码编译并运行良好,但我不知道我可以去哪里读取文件,或者我是否写过任何东西。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;

    System.out.println("filter invoked");

    InputStream in = null;
    OutputStream out = null;
    String inPath = context.getRealPath("/WEB-INF/template.txt");
    String outPath = context.getRealPath("/WEB-INF/output.txt");
    in = new FileInputStream(inPath);
    out = new FileOutputStream(outPath);

    OutputStreamWriter outstream = new OutputStreamWriter(out);
    outstream.write("hello");


    // pass the request along the filter chain
    chain.doFilter(request, response);
}

文件 template.txt 和 output.txt 位于 WEB-INF 目录中。我已经验证从文件中读取工作正常,但我无法验证对它们的写入。每次我写入 output.txt 时,文件仍然没有变化。

关于在 Web 应用程序环境中写入文件,我有什么不明白的地方?

【问题讨论】:

    标签: java eclipse web-applications servlet-filters


    【解决方案1】:

    您必须关闭您的流(这也会刷新它)(在finally 块中执行此操作)。顺便说一句,您可以使用 commons-io FileUtilsguava Files 这将使文件的处理更容易

    但是,一般的做法是不要在 webapp 目录中写入文件,因为下次重新部署时会丢失它们。选择/配置一个外部位置来存储它们。

    【讨论】:

    • 我在 finally 块中关闭了文件。我刷新了我的项目的目录树。我打开 /WEB-INF/output.txt 还是空白。
    • 你试过 fileutils / guava 选项了吗?
    • 其实我放弃了。无论如何,输出文件只是临时的,所以我只是使用了 StringBuilder。我不知道为什么我以前没有想到这一点。
    【解决方案2】:

    也不要忘记将它包装到 try finally 块中。

    OutputStreamWriter outstream = new OutputStreamWriter(out);
    try {
        outstream.write("hello");
    } finally {
        outstream.close();
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用类似下面的方法并尝试使用资源来处理流

      @Override
          public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
                  throws IOException, ServletException {
              // TODO Auto-generated method stub
              HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
      
              HttpServletResponse response = (HttpServletResponse) servletResponse;
              System.out.println(httpRequest.getRequestURI());
              System.out.println(httpRequest.getRequestURI().toLowerCase().endsWith("/v2/api-docs"));
              ByteArrayPrinter pw = new ByteArrayPrinter();
              // here i create a response wrapper
              HttpServletResponse wrappedResp = new HttpServletResponseWrapper(response) {
                  @Override
                  public PrintWriter getWriter() {
                      return pw.getWriter();
                  }
      
                  @Override
                  public ServletOutputStream getOutputStream() {
                      return pw.getStream();
                  }
      
              };
              System.out.println("before chaingin");
              // i get the response data from the stream
              chain.doFilter(httpRequest, wrappedResp);
              byte[] bytes = pw.toByteArray();
              String respBody = new String(bytes);
              System.out.println("in if" + respBody);
              if (httpRequest.getParameter("group") != null) {
      
      
      
                  byte[] newByte = pw.toByteArray();
                  String newString = new String(newByte);
                  System.out.println("new string:" + newString);
                  // i make a modification in the stream
                  String s = newString.replaceAll("basePath", "Vijayy");
                  System.out.println("printing s" + s);
      
                  // here i try to write to a file with the modification
                  try (FileOutputStream fos = new FileOutputStream(
                          new File(System.getProperty("user.dir") + "/static/openAPI.json"))) {
                      System.out.println("comin in if");
                      fos.write(s.getBytes());
      
      
                      FileCopyUtils.copy(
                              new FileInputStream(new File(System.getProperty("user.dir") + "/static/openAPI.json")),
                              response.getOutputStream());
      
                  } catch (FileNotFoundException ex) {
                      ex.printStackTrace();
                  }
                  // FileCopyUtils.copy(, out);
      
                  // IOUtils.copy(new ByteArrayInputStream(newString.getBytes()), response.getOutputStream());
      
              } else {
                  chain.doFilter(httpRequest, wrappedResp);
                  response.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE);
                  response.setContentLength(respBody.length());
                  response.getOutputStream().write(respBody.getBytes());
              }
      
               return;
          }
      

      ByteArrayprinter 是我为我的用例为 PrintStream 创建的包装器。同样,在您的情况下不需要考虑

      【讨论】:

        猜你喜欢
        • 2013-12-07
        • 1970-01-01
        • 1970-01-01
        • 2011-09-05
        • 2011-12-18
        • 2017-11-24
        • 1970-01-01
        • 2015-06-26
        • 1970-01-01
        相关资源
        最近更新 更多