A while ago saw a structure of exception handling, but always forget to send blog learning, today read and see this exception handling,
Try () {
}catch () {
}
Similar to this structure.
This structure is called try-with-resources. Automatic resource release.
This feature exists from the JDK1.7.
For example, the following code:
private static void Custombufferstreamcopy (file source, file target) {
InputStream FIS = null;
OutputStream fos = null;
try {
FIS = new FileInputStream (source);
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 ();
} finally {
Close (FIS);
Close (FOS);
}
}
private static void Close (Closeable closable) {
if (closable! = null) {
try {
Closable.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
The above code is very complex for exception handling,
For resources to close is also very cumbersome, then you can compare with the following:
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 ();
}
}
This code uses this Try-with-resources resource auto-release feature.
In Try () {
}catch () {
The resources are automatically closed after the end, and released. There is no need to write off manually.
Try () {} = = in Java try-with-resources resource Auto-release