我想在條件下使用 try-with-resources。我想從文件 f1 創(chuàng)建流,如果OK == true: try(FileInputStream fis1 = new FileInputStream(f1); FileInputStream fis2 = new FileInputStream(f1)) {...}或者從文件 f2 創(chuàng)建流,如果OK == false: try(FileInputStream fis1 = new FileInputStream(f2); FileInputStream fis2 = new FileInputStream(f2)) {...}OK 是我的程序中的布爾值。是否有可能在不引入重復(fù)代碼的情況下做到這一點,并且仍然保持代碼相當(dāng)易于閱讀?或者是否有另一種解決方案可以在沒有 try-with-resources 的情況下做同樣的事情?對解決方案的一些細節(jié)的評論將不勝感激。
1 回答

元芳怎么了
TA貢獻1798條經(jīng)驗 獲得超7個贊
您可以File在 try 塊之外使用 final對象:
final File file = OK ? f1 : f2;
try(FileInputStream fis1 = new FileInputStream(file);
FileInputStream fis2 = new FileInputStream(file)) {...}
除非有理由在同一個文件上創(chuàng)建兩個流,否則代碼應(yīng)該像 try(FileInputStream fis = new FileInputStream(file)){...}
添加回答
舉報
0/150
提交
取消