JAva最も簡潔なcloseリソースを閉じる方法
2216 ワード
JDK 7後のclose簡潔方式:1、最も簡潔なtry-with-resources文法糖:リソースを閉じるコードを書く必要がなく、リソースも閉じることができます.(注意変数宣言は括弧に書かれています)
2、一定のシーンでAutoCloseableインタフェースを使用する:資源の閉鎖に関わる限り、AutoCloseableインタフェースを継承し、close()方法を実現し、我々はすべて呼び出すことができる
3、複雑な元close方式:finallyで順次資源の解放を判断する
public static void main(String[] args) {
try (
FileOutputStream fos = new FileOutputStream("logs/1.log",true);
OutputStreamWriter os = new OutputStreamWriter(fos, "UTF-8");
){
os.write(date+" "+time+" "+i+"\r
");
}catch (Exception ex) {
ex.printStackTrace();
}
}
2、一定のシーンでAutoCloseableインタフェースを使用する:資源の閉鎖に関わる限り、AutoCloseableインタフェースを継承し、close()方法を実現し、我々はすべて呼び出すことができる
public static void main(String[] args) {
OutputStreamWriter os = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream("logs/1.log",true);
os = new OutputStreamWriter(fos, "UTF-8");
os.write(date+" "+time+" "+i+"\r
");
} catch (Exception e) {
e.printStackTrace();
} finally {
close(os);
close(fos);
}
}
public static void close(AutoCloseable closeable) {
if (closeable != null) {
try {
System.out.println(" !");
closeable.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、複雑な元close方式:finallyで順次資源の解放を判断する
public static void main(String[] args) {
OutputStreamWriter os = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream("logs/1.log",true);
os = new OutputStreamWriter(fos, "UTF-8");
os.write(date+" "+time+" "+i+"\r
");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}