Opening text file with Javascript script

Here is my code:

importClass(Packages.ij.IJ);

var testText = IJ.openAsString("test.txt");
print("type of testText: " + (typeof testText));
print(testText);

The logged output is:

type of testText: object
Error: file not found

Why isn’t testText a string? What is the “file not found” error about?

It is a Java string. Try this:

print("JavaScript type = " + (typeof testText) + "\n");
print("Java type = " + testText.getClass().getName() + "\n");

It should print:

JavaScript type = object
Java type = java.lang.String

You are using a relative path, and test.txt is not in ImageJ’s current working directory (which I am guessing, but not certain, is the ImageJ application directory). Try using an absolute path instead.

var testText = IJ.openAsString("C:\Users\abalter\Documents\OHSU\Example3_more than 100MB\Alignment_hnsccTMA-B_serial_Ex_p16_2\test.txt");
print("JavaScript type = " + (typeof testText) + "\n");
print("Java type = " + testText.getClass().getName() + "\n");
print(testText);

is giving:

JavaScript type = object
Java type = java.lang.String
Error: file not found

You are using backslashes, so you need to write C:\\Users\\abalter… because javascript and java use \ as an escape character.

I would suggest using forward slashes instead, which also work and do not have this problem.

I should have known that. But thanks for the tip about the forward slashes. I wouldn’t have thought they would work.