Sunday, February 24, 2008

File opening: EditorCookie or OpenCookie?

Yesterday I wanted to create XML document in memory and open it. On Netbeans Wiki there is explanation and sample code for creating text file and opening it using OpenCookie. But the sample code does not work with XML documents. I debugged the code and noticed that XmlDataObject does not contain OpenCookie class. Instead we have to use EditorCookie. And EditorCookie also works with text files too. So maybe the sample code on Netbeans Wiki should be updated to following:
    FileSystem fs = FileUtil.createMemoryFileSystem();
    FileObject fob = fs.getRoot().createData(name, "txt");

    DataObject data = DataObject.find(fob);
    EditorCookie cookie = (EditorCookie)data.getCookie(EditorCookie.class);;
Feel free to comment.


branajam said...

My name is James Branam and I'm the NetBeans Community Docs Manager. Your blog entry would make a fantastic tips & tricks entry for our Community Docs wiki ( Would you be willing to contribute it? If you need any help or have any questions, please contact me at I look forward to hearing from you.

Tim said...

If you just want to open a file of some unknown type (or known type but you want a text editor not potentially a graphical one), you probably just want

EditCookie ck = dataObject.getLookup().lookup(EditCookie.class);
if (ck != null) {
} else {
OpenCookie oc = dataObject.getLookup().lookup(OpenCookie.class);
if (oc != null) {;
} else {
//...similar thing for ViewCookie

However, if you need to navigate to a specific line, you're going to need EditorCookie eventually so it may make sense to start with that.

-Tim Boudreau

damir said...

You are right Tim. Thanks.
On James suggestion I putted this post on Community Docs wiki page

robin said...


I have been digging into this problem of open the Netbeans default editor for some of our temporary data.

I tried your solution (which works really nice) but the last think I want to get is any kind of event when the user tries to save the file, so I can save properly this file. Any hint there ?

cheers, robert