user9160422
user9160422

Reputation: 45

Create a FileInputStream in a try-with-resources from different files based on a condition

I want to use try-with-resources with a condition. I want to create streams from file f1 if OK == true:

    try(FileInputStream fis1 = new FileInputStream(f1); FileInputStream fis2 = new FileInputStream(f1)) {...}

Or create the stream from file f2 if OK == false:

  try(FileInputStream fis1 = new FileInputStream(f2); FileInputStream fis2 = new FileInputStream(f2)) {...}

OK is a boolean value I have in my program.

Would it be possible to do this without introducing duplicate code and still keep the code reasonably easy to read? Or is there another solution that does the same thing without the try-with-resources?

Comments with some details about the solution would be appreciated.

Upvotes: 0

Views: 140

Answers (1)

ernest_k
ernest_k

Reputation: 45339

You can use a final File object outside the try block:

final File file = OK ? f1 : f2;

try(FileInputStream fis1 = new FileInputStream(file);
    FileInputStream fis2 = new FileInputStream(file)) {...}

Unless there's a reason to create two streams on the same file, the code should be as simple as try(FileInputStream fis = new FileInputStream(file)){...}

Upvotes: 1

Related Questions