Raniz Raniz - 8 months ago 30
Java Question

Try-with-resources when calling super constructor

Is there any good way of using try-with-resources when opening an

in a constructor and then passing that to a super constructor?

Basically what I want to do is this:

public class A {
public A(InputStream stream) {
// Do something with the stream but don't close it since we didn't open it

public class B {
public B(File file) {
// We open the stream so we need to ensure it's properly closed
try (FileInputStream stream = new FileInputStream(file)) {
super(new FileInputStream(file));

But, of course, since
must be the first statement in the constructor this isn't allowed. Is there any good way of achieving this?


Consider using a static factory method instead of using the constructor directly. Make at least B's constructor private, and create a method such as

private B(InputStream is) {
    // Whatever else is needed

public static B newInstance(File file) {
    B result;
    try (FileInputStream stream = new FileInputStream(file)) {
        result = new B(stream);
    // Further processing
    return result;