关闭传递给 MultipartFormDataOutput 的流

Closing Streams passed to MultipartFormDataOutput

Resteasy docs 没有解释谁负责关闭传递给 MultipartFormDataOutput 的流。让我们考虑以下示例:

WebTarget target = ClientBuilder.newClient().target("url");
MultipartFormDataOutput formData = new MultipartFormDataOutput();
FileInputStream fis1 = new FileInputStream(new File("/path/to/image1"));
FileInputStream fis2 = new FileInputStream(new File("/path/to/image2"));
formData.addFormData("image", fis1, MediaType.APPLICATION_OCTET_STREAM_TYPE);
formData.addFormData("image", fis2, MediaType.APPLICATION_OCTET_STREAM_TYPE);
Entity<MultipartFormDataOutput> entity = Entity.entity(formData, MediaType.MULTIPART_FORM_DATA);
Response response = target.request().post(entity);

fis1fis2 会被 resteasy 关闭还是用户应该注意关闭这些流?

我建议使用 try-with-resource 以确保它们将被关闭。

WebTarget target = ClientBuilder.newClient().target("url");
MultipartFormDataOutput formData = new MultipartFormDataOutput();

try(FileInputStream fis1 = new FileInputStream(new File("/path/to/image1")));
    FileInputStream fis2 = new FileInputStream(new File("/path/to/image2")))
{
  formData.addFormData("image", fis1, MediaType.APPLICATION_OCTET_STREAM_TYPE);
  formData.addFormData("image", fis2, MediaType.APPLICATION_OCTET_STREAM_TYPE);
  Entity<MultipartFormDataOutput> entity = Entity.entity(formData, 
  MediaType.MULTIPART_FORM_DATA);
  Response response = target.request().post(entity);
}

所以我可以自己回答我的问题,希望有人能从中受益。

Resteasy 将关闭传递的流。在我的例子中,InputStreamProvider 将负责关闭 FileInputStream.

     public void writeTo(InputStream inputStream, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException
   {
           LogMessages.LOGGER.debugf("Provider : %s,  Method : writeTo", getClass().getName());
       try
       {
           int c = inputStream.read();
           if (c == -1)
           {
               httpHeaders.putSingle(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(0));
               entityStream.write(new byte[0]); // fix RESTEASY-204
               return;
           }
           else
               entityStream.write(c);
         ProviderHelper.writeTo(inputStream, entityStream);
       }
       finally
       {
         inputStream.close();
       }
   }