javahtmlimageswinghtmleditorkit

Using HTMLEditorKit in Java, how do I find what local file path <img src=...> tags will use?


I've got a java app running, and I'm using the HTMLDocument/HTMLEditorKit functionality to build my chat room. So far with plenty of success as far as building my stylesheet, inserting text messages, and so forth.

So now I've come to... images! I had thought that if I were adding tags such as:

<img src="myimage.png"> 

... that my file then just needed to be in the same directory as the java app when I ran it. But I've run through all sorts of things and tried subdirectories, and it can't seem to find my local image. (It finds them just fine off the web with "http://etcetcetc").

All the documentation I search for these things mostly talks about the directory "your html file is in", and of course I don't "really" have an html file, just a virtual one.

Is there a way to ask it what directory it THINKS it's reading from?

I tried putting the file in the directory that resulted from:

System.getProperty("user.dir");

... but no joy.

Looking for some kind of relative-pathing here, such that image files eventually installed on a user's machine along with the app would be able to be displayed.

[EDIT: whoops, fixed my HTML example]


Solution

  • Okay, what I have discovered (from tidbits gleaned in a few tangentially-related answers to other questions) is that I needed to create a URL item, and then get it filled by ClassLoader or a similar method.

    For example one person got his thingy going with:

    String filename = getClass().getClassLoader().getResource("res/Kappa.png").toString();
    String preTag="<PRE>filename is : "+filename+"</PRE>";
    String imageTag="<img src=\""+filename+"\"/>";
    kit.insertHTML(doc, doc.getLength(), preTag+imageTag, 0, 0, HTML.Tag.IMG);
    

    Meanwhile, drawing from this hint the method that finally got MY stuff running "the best" was:

        URL url;
        String keystring = "<img src=\"";
        String file, tag, replace;
        int base;
        while (s.toLowerCase().contains(keystring)) { // Find next key (to-lower so we're not case sensitive)
            //There are undoubtedly more efficient ways to do this parsing, but this miraculously ran perfectly the very first time I compiled it, so, you know, superstition :)
            base = s.toLowerCase().indexOf(keystring);
            file = s.substring(base + keystring.length(), s.length()).split("\"")[0]; // Pull the filename out from between the quotes
            tag  = s.substring(base, base + keystring.length()) + file + "\""; // Reconstruct the part of the tag we want to remove, leaving all attributes after the filename alone, and properly matching the upper/lowercase of the keystring                        
    
            try {
                url = GameModule.getGameModule().getDataArchive().getURL("images/" + file);
                replace = "<img  src=\"" + url.toString() + "\""; // Fully qualified URL if we are successful. The extra
                                                                    // space between IMG and SRC in the processed
                                                                    // version ensures we don't re-find THIS tag as we
                                                                    // iterate.
            } catch (IOException ex) {
                replace = "<img  src=\"" + file + "\""; // Or just leave in except alter just enough that we won't find
                                                        // this tag again.
            }
    
            if (s.contains(tag)) {
                s = s.replaceFirst(tag, replace); // Swap in our new URL-laden tag for the old one.
            } else {
                break; // BR// If something went wrong in matching up the tag, don't loop forever
            }
        }
    
        //BR// Insert a div of the correct style for our line of text. 
        try {
            kit.insertHTML(doc, doc.getLength(), "\n<div class=" + style + ">" + s + "</div>", 0, 0, null);
        } catch (BadLocationException ble) {
            ErrorDialog.bug(ble);
        } catch (IOException ex) {
            ErrorDialog.bug(ex);
        }
        conversation.update(conversation.getGraphics()); //BR// Force graphics to update
    

    My package runs under VASSAL (the game platform), and so it was ideal for me to be able to pull things from my VASSAL module's data archive (zip file), though at the time I asked the question I would have been happy just to find out anywhere I could make it find an image file and getting it out of the data archive was a later stretch goal.

    You can see my strategy here is to let the html (which might be generated by another module designer, not me) have simple filenames referenced in the source tags (e.g. src="dice.png") and I go parse those out and replace them with the result of the URL query if it is successful.

    If someone has a more complete answer to the thrust of the original question (where on earth does HTMLEditorKit look for local PATHS? -- what is the default local path? How can I make it look in my present working directory, or the directory the app is running from, or really anything local like that) then please do post it here for posterity, because although this got me running I don't feel like it's a comprehensive answer to the original question.