How to check if a file exists in ImageJ's Javascript

Hi,
I would like to check if a file exists. I thought of doing it with the standard method in Java. I imported:

importClass(Packages.java.io.File);

And I used the following code:

fl = File("/Users/avitalsteinberg/Javascript /exampleProcstkInput_output/selection1s2Results666.txt");
if( fl.isFile()){
    print("This file exists");
}

If the file specified in the parentheses exists, the code works. But if it doesn’t, I get a Java null pointer exception.

What’s the best way to check if a file exists using ImageJ’s Javascript?

Thanks,
Avital

Use the exists() method from the File class:

if( fl.exists()){
    print("This file exists");
}

Thanks, Jan, but I get the same problem also when I use the exist() method. The problem is that when I construct fl:

fl = File("/Users/avitalsteinberg/Javascript /exampleProcstkInput_output/selection1s2Results666.txt");

I get a Java null pointer exception if the file doesn’t exist.

Thanks,
Avital

This gives a TypeError on my system, not a NullPointerException:

TypeError: [JavaClass java.io.File] is not a function

In Javascript (as in Java), use the new keyword to create a new instance of a class. This should work:

fl = new File("/Users/avitalsteinberg/Javascript /exampleProcstkInput_output/selection1s2Results666.txt");

Thanks, Jan - for some reason, the warning disappeared. (It was a console window that appeared with red text saying that there’s a java null pointer exception, but it still ran) It’s actually not related to any changes that I made. I’m not sure why the warning appears or disappears kind of randomly, but my script is working.

It may have been left over from an old script. Click the “Clear” button, then click “Show Output” or “Show Errors” and then “Clear” again. This erases old output (i.e.: stdout), as well as error messages (i.e.: stderr).

Thanks - I’ll try that the next time the warning appears.