Search code examples
javaservletsstreamwriter

Simplest way to write bytes to a writer?


I have written an implementation of HttpServletResponse and I am overriding a method getOutputStream which needs to return a ServletOutputStream. The data that is written to said stream must be encoded using UTF-8 and then written to a separate Writer that was passed in the constructor.

Here is my pseudo-code.

class StreamResponse implements HttpServletResponse {
    private final PrintWriter pw;
    StreamResponse(PrintWriter pw) {
        this.pw = pw;
    }
    public PrintWriter getWriter() throws IOException {
        return pw;
    }
    public ServletOutputStream getOutputStream() throws IOException {
        // what do I do?
    }
    // other methods overridden
}

How can I most simply return an OutputStream that outputs to Writer pw? I would rather not include extra .jar files for this, but am open to including an additional .java file if that is the way to do it.

What would you recommend?


Solution

  • You can use org.apache.commons.io.output.WriterOutputStream

    It has multiple constructors e.g.

    public WriterOutputStream(Writer writer, String charsetName)
    

    or wider one

    public WriterOutputStream(Writer writer, Charset charset, int bufferSize, boolean writeImmediately)
    

    Just wrap your writer and return new WriterOutputStream(pw, theCharSet)

    UPDATE: If you don't want to include the jar you can look at the code (it's rather simple) to get the main idea and write own OutputStreamWriter implementation