Create directory in Javascript

In regular macro programming, you can create a directory with

File.makeDirectory;

http://imagej.net/developer/macro/functions.html#F

I tried in Javascript

importPackage(Packages.ij.File);
File.makeDirectory("a");

But I get

Error: Java class "java.io.File" has no public instance field or method named "makeDirectory". 

Use File.mkdir().

Error: Java class “java.io.File” has no public instance field or method named “mkdir”.

Still getting an error.

You need to create a new File object pointing at the desired directory path, and then call the mkdir method on it to create it on disk. See this article on object oriented JavaScript for an introduction to these concepts, if you aren’t familiar with them.

I’m familiar with object oriented Javascript. But this has to do with the way Java libraries are exposed in ImageJ, or maybe it’s just Rhino. This stuff isn’t terribly well documented.

importPackage(Packages.ij.File);
var fileObject = new File(folder);
directoryName = folder + "testDirectory";
print("making directory " + directoryName);
print(fileObject.listFiles());
fileObject.mkdir(directoryName);
[Ljava.io.File;@6de78a
Error: Can't find method java.io.File.mkdir(string). (<Unknown source>#19) in <Unknown source> at line number 19

The output from print(fileObject.listFiles()) is telling me something about what is going wrong, but I’m not sure what.

You’re directly interacting with the Java classes here, so the Javadoc for ImageJ1 and (in the case of java.io.File) Java itself should help you. Please feel free to add to the Javascript scripting page whatever you think is missing.

To your specific case:

importPackage(Packages.ij.File);

There’s no such package. I wonder why you didn’t get an error message here. Use importClass(Packages.java.io.File); instead.


[Ljava.io.File;@6de78a
Error: Can't find method java.io.File.mkdir(string).

Again, look at the javadoc of java.io.File: the mkdir() method doesn’t take any arguments. The directory name has to be provided in the contructor of the File object.

importClass(Packages.java.io.File);
var pathToNewDirectory = "/path/to/folder/testDirectory";
var fileObject = new File(pathToNewDirectory);
fileObject.mkdir();

Knowing the macro command File.makeDirectory, you could have found this in Functions.java:

1 Like

OK. I’m starting to see how this works. I’ll use that as a reference.

1 Like