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?
You have to close your stream (which will flush it as well) (do that in a
finallyblock). Btw you can use commons-ioFileUtilsor guavaFileswhich will make the handling of files easierHowever, 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.