I'm using IOUtils
to parse JSON
from a HttpServletRequest request
:
baseRequest.setAuthentication(null);
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
PrintWriter writerResponse = response.getWriter();
-> String data = IOUtils.toString(request.getInputStream(), "UTF-8"); <-
But Eclipse complains of a potential resource leak:
Potential resource leak: '<unassigned Closeable value>' may not be closed
Even when I surround it with a try/finally
block and close via IOUtils.closeQuietly()
the error persists like a stubborn mule.
String data = "";
try {
data = IOUtils.toString(request.getInputStream(), "UTF-8");
} catch (IOException e) {
} finally {
IOUtils.closeQuietly(request.getInputStream());
}
What is causing this error and how do I fix it?
P.S
While the code below:
try {
String data = IOUtils.toString(request.getInputStream(), "UTF-8");
} catch (IOException e) {
} finally {
IOUtils.closeQuietly(request.getInputStream());
}
does not throw any error, as soon as I try using the value 'data' anywhere in my code (even in the try statement) the error shows up again.
CodePudding user response:
The error is correct. getInputStream
may well return a new input stream each time you call getInputStream
, so closing a new input stream doesn't help.
Save the input stream in a variable. Best of all, use try-with-resources:
try (InputStream stream = request.getInputStream()) {
data = IOUtils.toString(stream, "UTF-8");
}