作者:@红薯
從 Java 7 build 105 版本開始,Java 7 的編譯器和運行環境已支援新的 try-with-resources 語法,稱為 ARM (Automatic Resource Management) ,自動資源管理。
新的語句支援包括流以及任何可關閉的資源,例如,一般我們會編寫如下代碼來釋放資源:
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();
}
}
}
而使用 try-with-resources 語法來簡化如下:
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();
}
}
or
public static void customBufferStreamCopy(String[] args) throws Exception{
@Cleanup InputStream in = new FileInputStream(args[0]);
@Cleanup OutputStream out = new FileOutputStream(args[1]);
byte[] buf = new byte[8192];
int i;
while ((i = in.read(buf)) != -1) {
out.write(buf, 0, i);
}
}
沒有留言:
張貼留言