Java開發中IO流的使用以及異常的處理記錄
先來看一些之前使用IO流的代碼
C1 之前習慣的寫法:
File f = new File(outputPath + projectName + projectVersion+"DirTreeShowMaker.txt");
try {
if (!f.exists()) {
f.createNewFile();
}
fw = new FileWriter(f);
out = new BufferedWriter(fw);
out.write(dirTreeRecords, 0, dirTreeRecords.length() - 1);
out.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
將流的開啟和關閉全部放在了try塊當中,如果不關閉,那么這個IO資源就會被一直占用,這樣別的地方想用就沒有辦法用了,所以這造成資源的浪費。而且這個時候關閉資源由于沒有寫在finally中,如果這個上面的某個地方出現一個異常,整個就關不掉了
C2 放在了try catch外邊
File f = new File(outputPath + projectName + projectVersion+"DirTreeShowMaker.txt");
try {
if (!f.exists()) {
f.createNewFile();
}
fw = new FileWriter(f);
out = new BufferedWriter(fw);
out.write(dirTreeRecords, 0, dirTreeRecords.length() - 1);
} catch (IOException e) {
e.printStackTrace();
}
out.close();
fw.close();
問題也是比較類似的,這里也是考慮到了關閉資源,但是這樣是關不掉的,因為一旦上面出了問題,下面的語句就執行不到了,所以要放在finally塊里才能關閉。
C3 放在finally里面
File f = new File(outputPath + projectName + projectVersion+"DirTreeShowMaker.txt");
try {
if (!f.exists()) {
f.createNewFile();
}
fw = new FileWriter(f);
out = new BufferedWriter(fw);
out.write(dirTreeRecords, 0, dirTreeRecords.length() - 1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//該斷言僅在debug版本有效,在release版本當中是無效的
//assert out != null;
//如果上面的資源當中出現了異常,try當中
if ( null != out ){
out.close();
}
if (null != fw ){
fw.close();
}
} catch (IOException e) {
System.out.println("在編排包信息文件生成中"+e.getMessage());
}
}
但是如果流一旦多了就會導致整個語句結構非常繁瑣,因為會循環嵌套try-catch-finally語句,尤其是在finally子句中,close()方法也會拋出異常,就導致每次都需要使用try-catch來包裹close()方法
較為優雅的方法
因此在java7之后,可以使用try-with-resources語句來釋放java流對象
相對于C3當中啰嗦的寫法
下面來看使用了try-with-resources
后的效果:
if (!f.exists()) {
f.createNewFile();
}
try (FileWriter fw = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fw);) {
out.write(dirTreeRecords, 0, dirTreeRecords.length() - 1);
} catch (IOException e) {
e.printStackTrace();
}
try-with-resources
將會自動關閉try()
中的資源,并且將先關閉后聲明的資源。
如果不``catch IOException`整個結構就會更加完美,Oh!Nice
if (!f.exists()) {
f.createNewFile();
}
try (FileWriter fw = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fw);) {
out.write(dirTreeRecords, 0, dirTreeRecords.length() - 1);
}