I want to do this with gson when reading from a json file:
JsonReader reader = new JsonReader(new InputStreamReader(
new FileInputStream(filename)));
JsonParser jsonParser = new JsonParser();
return jsonParser.parse(reader).getAsJsonObject();
I'll do more things with the returned JsonObject somewhere else.
My question is that whether this is okay since I never close the reader.
From the gson API of JsonReader, it shows that JsonReader implements AutoClosable. Does that mean JsonReader will be automatically closed? If so, when is it closed and how?
Thank you.
Yes, you have to close your reader. As shmosel points out AutoClosable can be used for try-with-resource statements which were introduced in Java 7.
Here is how you could adjust your code:
try(JsonReader reader = new JsonReader(new InputStreamReader(
new FileInputStream(filename))))
{
JsonParser jsonParser = new JsonParser();
return jsonParser.parse(reader).getAsJsonObject();
}