Posted by
Michael Schmid on
Sep 01, 2014; 4:12pm
URL: http://imagej.273.s1.nabble.com/How-to-read-and-write-files-using-a-java-plugin-tp5009393p5009450.html
Hi Avital,
if you know what to write in a macro, here is a simple way how to find the corresponding commands for a plugin:
- Have a look at the static IJ class. Many macro commands have equivalents there.
- If you don't find it in IJ, have a look at ij.macro.Functions.java. There you will find the code executed upon calling one of the ImageJ built-in macro functions.
Example:
Reading a file into a string, macro command File.openAsString(path):
IJ.openAsString(String path)
For writing a file, you may find some code in ij.macro.Functions.openFile(), closeFile() etc:
FileOutputStream fos = new FileOutputStream(path);
BufferedOutputStream bos = new BufferedOutputStream(fos);
PrintWriter writer = new PrintWriter(bos);
writer.println(myString);
writer.close();
---
Another option is using java.util.Properties; this is essentially a Hashtable that can be used to nicely save pairs like
myKey1=myValue1
myKey2=myValue2
or an XML file ('flat' XML file with key-value pairs only, no hierarchies). Values must be Strings, but you can convert them back to numbers with, e.g., ij.utils.parseDouble.
In that case, you can call ij.io.SaveDialog.java and ij.io.OpenDialog.java for the file dialogs, then create the java.io.FileOutputStream.html and FileInputStream streams required by the Properties.store and Properties.load.
Michael
________________________________________________________________
On Aug 28, 2014, at 10:40, Avital Steinberg wrote:
> Hi,
> My plugin has a function (function A) that calculates results that I would
> like to save in a file. These results will be used by another function,
> which means that function B has to read this file (that should be chosen by
> the user). Function B will use the parameters that were saved in it to do
> calculations.
>
> It would have been easy to do with the ImageJ macro, but I am trying to do
> it in a Java plugin. What is the best way to do it?
>
> Thank you,
> Avital
--
ImageJ mailing list:
http://imagej.nih.gov/ij/list.html