Try-with-Resources जावा 7 में पेश किया गया था। इसका उपयोग करने का उद्देश्य उपयोग के बाद संसाधनों को स्वचालित रूप से बंद करना है। सीमा यह है कि संसाधन को try से पहले या try स्टेटमेंट के अंदर घोषित करने की आवश्यकता होती है, यदि नहीं तो यह कंपाइलेशन एरर फेंकता है।
जावा 9 ने try-with-resources में सुधार किया है और अब ऑब्जेक्ट को try स्टेटमेंट के अंदर घोषित करने की आवश्यकता नहीं है।
नीचे दिए गए उदाहरण में, हमने try-with-resources अवधारणा को लागू किया है।
उदाहरण
import java.io.*;
public class TryWithResourceTest {
public static void main(String[] args) throws FileNotFoundException {
String line;
Reader reader = new StringReader("tutorialspoint");
BufferedReader breader = new BufferedReader(reader);
try(breader) {
while((line = breader.readLine()) != null) {
System.out.println(line);
}
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
आउटपुट
tutorialspoint