In our normal development work, often need to read and write stream, in this process the most egg pain is a variety of try and catch, and then finally you can not forget to close the flow, so as to avoid the resource leakage, this set down feel particularly bloated. The following is a simple example:
The old resource opens the way
bufferedreader br = null;
try {
br = new BufferedReader (New FileReader (
"/users/mrsimple/update_hosts.py"));
StringBuilder sb = new StringBuilder ();
String line = "";
while (line = Br.readline ())!= null) {
sb.append (line). append ("\ n");
System.out.println (Sb.tostring ());
} catch (FileNotFoundException e) {
e.printstacktrace ();
} catch (IOException e) {
e.printstacktrace (); c14/>} finally {
if (br!= null) {
try {
br.close ();
} catch (IOException e) {
e.printstacktrace ();
}
}
} End of Finaly
Fortunately, Java 7 introduced two very useful features, that is, automatic shutdown of the stream and catch multiple exceptions. The code required to implement the same functionality after using these two new features is as follows:
Resource Open in Java 7
try (bufferedreader newbr = new BufferedReader (New FileReader (
"/users/mrsimple/update_ hosts.py ")) {
StringBuilder sb = new StringBuilder ();
String line = "";
while (line = Newbr.readline ())!= null) {
sb.append (line). append ("\ n");
System.out.println (Sb.tostring ());
} catch (IOException | FileNotFoundException e) {
e.printstacktrace ();
}
When you build a Newbr object in a try block, the object shuts down automatically at the end of the block, eliminating the developer from manually shutting down the stream. Catch multiple exceptions also makes the code more concise.