我想在条件下使用 try-with-resources。我想从文件 f1 创建流,如果OK == true: try(FileInputStream fis1 = new FileInputStream(f1); FileInputStream fis2 = new FileInputStream(f1)) {...}或者从文件 f2 创建流,如果OK == false: try(FileInputStream fis1 = new FileInputStream(f2); FileInputStream fis2 = new FileInputStream(f2)) {...}OK 是我的程序中的布尔值。是否有可能在不引入重复代码的情况下做到这一点,并且仍然保持代码相当易于阅读?或者是否有另一种解决方案可以在没有 try-with-resources 的情况下做同样的事情?对解决方案的一些细节的评论将不胜感激。
1 回答
元芳怎么了
TA贡献1798条经验 获得超7个赞
您可以File在 try 块之外使用 final对象:
final File file = OK ? f1 : f2;
try(FileInputStream fis1 = new FileInputStream(file);
FileInputStream fis2 = new FileInputStream(file)) {...}
除非有理由在同一个文件上创建两个流,否则代码应该像 try(FileInputStream fis = new FileInputStream(file)){...}
添加回答
举报
0/150
提交
取消