Consider a scenario where you want to write a download file for the system and cache it locally. You will use InputSteam and OutputStream classes. You may write as follows:
InputStream is = null; OutputStream os = null; try { is = new FileInputStream(""); os = new FileOutputStream(""); //Download file code //Code saved locally } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } }
In the finally code block, 14 lines of code are written to close the two IO streams. If a lot of if is written every time IO is used else, it's annoying. Is there any way to do it in one line of code? Check the source code of InputStream and OutputStream abstract classes, and find that they all implement the common interface Closeable. In fact, all Stream classes in java must implement this interface, so it's easy to do.
We can design a tool class as follows:
public class IOUtil { public static void close(Closeable... closeableList) { try { for (Closeable closeable : closeableList) { if (closeable != null){ closeable.close(); } } } catch (IOException e) { e.printStackTrace(); } } }
Then, in the finally code block, you can write as follows:
finally{ /* These codes can be omitted if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } */ //All you need is the following line of code IOUtil.close(is, os); }
Is it convenient? This tool class uses the idea of variable parameters and interface isolation. Writing code like this is not only convenient, but also a lot more readable, isn't it?