Woodchuck
Woodchuck

Reputation: 4474

java new file not returning a boolean when part of a conditional

In my Java program, this creates a directory and returns a boolean true when successful:

new File(String.valueOf(subdir)).mkdir();

So why does that not work as the second part of this boolean? I.e., the directory does not get created and it does nt return a boolean true.

if (!subdir.exists() || new File(String.valueOf(subdir)).mkdir()) {
    logger.error("subdir not created");
}

Upvotes: 0

Views: 63

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19575

The second condition won't be calculated if the first condition is already true and the conditions are joined with OR || operator.

Similarly, second condition is not calculated for AND && operator if the first condition is false.

It is so called short circuit for logical operations - because it does not make sense to continue evaluation of other terms if the result of the expression is already defined:

false && any_operand == false
true || any_operand == true

So, in your case you need to use && in the condition and possibly use File::mkdirs() method to create parent directories if they don't exist:

if (!maint.exists() && !maint.mkdirs()) {
    logger.info("no directories {} created", maint);
}

Upvotes: 1

Related Questions