如何从 servlet-filter 写入文件并在 Eclipse 中读取它?

发布于 2024-12-10 10:28:46 字数 995 浏览 0 评论 0原文

我想从我的过滤器写入一个文件,然后能够在 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 应用程序环境中写入文件,我不明白什么?

I want to write to a file from my filter and then be able to read it in Eclipse to make sure I've written to it correctly.

This code compiles and runs fine, but I don't know where I can go to read the file or if I've even written anything at all.

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

The files template.txt and output.txt are in the WEB-INF directory. I have verified that reading from the files works fine but I can't verify writing to them. Each time I write to output.txt there is still no change to the file.

What am I not understanding about writing to files in the web-application environment?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

手长情犹 2024-12-17 10:28:46

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

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

You have to close your stream (which will flush it as well) (do that in a finally block). Btw you can use commons-io FileUtils or guava Files which will make the handling of files easier

However, the general practice is not to write files in the webapp directory, because you will lose them on the next redeploy. Choose/configure an external location to store them.

太阳公公是暖光 2024-12-17 10:28:46

另外不要忘记将其包装到 try finally 块中。

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

Also do not forget to wrap it into try finally block.

OutputStreamWriter outstream = new OutputStreamWriter(out);
try {
    outstream.write("hello");
} finally {
    outstream.close();
}
回眸一笑 2024-12-17 10:28:46

您可以使用类似下面的内容,并让尝试使用资源来处理流。

@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 创建的包装器。同样,在您的情况下不需要考虑这一点

You could use something like below and let the try with resources to handle the stream

@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 is a wrapper I created for the PrintStream for my use case. Again that needed not be considered in your case

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文