3

I am learning how to write macros in ImageJ. I have the user select a folder where data is stored, e.g.,

path=getDirectory("Choose a data folder");

Once the user has selected the folder, e.g.,

path = D:\data_superfolder\data_folder

I then need to access a file that is up one level, e.g.,

newpath = D:\data_superfolder

In Matlab to move up one level all i need to do is,

cd('..')

which is super simple, but I've read through the ImageJ user manual I can't find similar code. How do I do this?

Thanks!

Jan Eglinger
  • 3,995
  • 1
  • 25
  • 51
Alna
  • 57
  • 1
  • 7

2 Answers2

2

You can append /.. to a directory path to refer to its parent folder.

Here is an example macro that prompts the user to choose a directory, then lists the contents of its parent.

path = getDirectory("Choose a folder");
list = getFileList(path + "/..");
for (i = 0; i < list.length; i++) {
    print(list[i]);
}
ctrueden
  • 6,751
  • 3
  • 37
  • 69
  • Thanks for the response, But I can't get it to work: path = getDirectory("Choose folder") superpath= path+"\.."; run("Open...", "open = ["+superpath+"image.tif"+"] errors with: File is not in a supported format, a reader plugin is not available, or it was not found. F:\Data\2015-04-02\..image.tif It just added two dots between the end of the folder and the file name, but I want it to change directories to find the image file in "F:\Data", and open it after the user selects the data folder for a specific experiment date. Thanks! – Alna Apr 13 '15 at 18:32
  • 1
    Your path would need to be `F:\Data\2015-04-02\..\image.tif`. That is, there must be a slash separating the `..` and the filename. Try using `superpath+"\image.tif"` instead. – ctrueden Apr 13 '15 at 19:06
  • OK, adding the backslash helped, but I had to use two: F:\Data\2015-04-09\..\\image.tif And then it worked. Thanks!!! – Alna Apr 14 '15 at 00:41
  • 1
    Good point; backslash is the escape character, so you have to write "\\" to mean one literal backslash. This is why I suggested you use forward slash instead (/), since that works on all platforms including Windows, and avoids that issue. – ctrueden Apr 14 '15 at 14:45
  • I see, I use both matlab and imageJ and I use the backslash exclusively and I was just trying to be consistent. Thanks for the help :) – Alna Apr 14 '15 at 20:18
1

Ok, I had a similar problem, tried the fix suggested here and I couldn't get it to work... However, what worked for me was to define a new variable corresponding to the parent of your initial input directory, using the function File.getParent().

in example:

path = getDirectory("Choose a folder");
parent_path = File.getParent(path);
list = getFileList(parent_path);

for (i = 0; i < list.length; i++) {
print(list[i]);
}

so in your case, once the user has selected the folder, e.g.,

path = D:\data_superfolder\data_folder

the variable "parent_path" will be:

parent_path = D:\data_superfolder

Cheers!