Reputation: 7859
My code is reading an HTML page from the web and I want to write good code, so I would like to close the resources using try-with-resources or finally block.
With the following code it seems impossible to use either of them to close "in".
try {
URL url = new URL("myurl");
BufferedReader in = new BufferedReader(
new InputStreamReader(
url.openStream()));
String line = "";
while((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (IOException e) {
throw new RuntimeException(e);
}
Would you be able to write the same code using try-with-resources or finally?
Upvotes: 0
Views: 2326
Reputation: 70564
I don't see any particular difficulty with the following:
try (BufferedReader in = new BufferedReader(new InputStreamReader(
new URL("myurl").openStream()))) {
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
Is it not what you're looking for?
Upvotes: 3