Quantcast
Channel: Techie Stuffs - Blogs on technology
Viewing all articles
Browse latest Browse all 28

AutoCloseable - try with resources block

$
0
0
Java 7 introduces a new feature to close any resources which is open and missed to close int the code. If a file is opened and we don't really need to worry about closing that any more. The Autocloseable interface referenced in the try block will be closed automatically. Around 533 classes in Java implements the autocloseable interface.


Sample code : 


private static void customBufferStreamCopy(File source, File target) {
try (InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target)){
byte[] buf = new byte[8192];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
e.printStackTrace();
}

}



Viewing all articles
Browse latest Browse all 28

Trending Articles