title: Serving static files with Jersey - Error while closing the output stream in order to commit response
body: <p>I'm trying to implement a project that will basically serve static files that are located in a folder of the project. I'm using Jersey 2.22.1. It should be a method that receives a filename and answers with the requested file.</p>
  
  <p>Implementation:</p>
  
  <pre><code>@GET
  @Path("/{filename : .*}")
  public Response getFile(@PathParam("filename") String filename) {
  
      String f = getFileFromSomewhere(filename);
  
      StreamingOutput fileStream =  new StreamingOutput()
      {
          @Override
          public void write(java.io.OutputStream output) throws IOException, WebApplicationException
          {
              try
              {
                  java.nio.file.Path path = Paths.get(f);
                  byte[] data = Files.readAllBytes(path);
                  output.write(data);
                  output.flush();
              }
              catch (Exception e)
              {
                  throw new WebApplicationException("File Not Found !!");
              }
          }
      };
  
      return Response
              .ok(fileStream)
              .build();
  }
  </code></pre>
  
  <p>The following error occurs:</p>
  
  <pre><code>GRAVE: Error while closing the output stream in order to commit response.
  java.lang.IllegalStateException: getWriter() has already been called for this response
  at org.apache.catalina.connector.Response.getOutputStream(Response.java:628)
  </code></pre>
  
  <p>The files are being requested by a browser and i have noticed that the error only occurs with .js files (it's ok with.html and .css files). There are reasons why this files should be served by this method and not by the conventional mode.</p>
  
  <p><a href="https://i.stack.imgur.com/XOBCj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XOBCj.png" alt="enter image description here"></a></p>
  
  <p>Any ideas?</p>