我想使用带有条件的try- with -resources。如果为OK == true,我想从文件f1创建流
try(FileInputStream fis1 = new FileInputStream(f1); FileInputStream fis2 = new FileInputStream(f1)) {...}或者,如果为OK == false,则从文件f2创建流
try(FileInputStream fis1 = new FileInputStream(f2); FileInputStream fis2 = new FileInputStream(f2)) {...}OK是我的程序中的一个布尔值。
有没有可能在不引入重复代码的情况下做到这一点,同时仍然保持代码的易读性?或者,有没有另一种解决方案,可以在不使用资源的情况下做同样的事情?
与解决方案的一些细节的意见将不胜感激。
发布于 2018-08-22 16:59:47
您可以在try块之外使用最终的File对象:
final File file = OK ? f1 : f2;
try(FileInputStream fis1 = new FileInputStream(file);
FileInputStream fis2 = new FileInputStream(file)) {...}除非有理由在同一个文件上创建两个流,否则代码应该像try(FileInputStream fis = new FileInputStream(file)){...}一样简单
https://stackoverflow.com/questions/51963188
复制相似问题