2
package htmldocsave;

import java.io.IOException;

import javax.swing.text.BadLocationException;
import javax.swing.text.html.*;

import java.io.*;

public class HTMLDocSave 
{
    public static void main(String[] args)
    {
        HTMLDocument doc = new HTMLDocument();
        HTMLEditorKit kit = new HTMLEditorKit();

        File f = new File("greeting.html");

        try 
        {
            kit.insertHTML(doc,doc.getLength(),"<b>Hello</b>",0,0,null);
            FileOutputStream fos = new FileOutputStream(f);

            ???????????????????????????
                    fos.close();
        } 
        catch (BadLocationException | IOException e) 
        {
            e.printStackTrace();
        }

    }
}

How to save a HTML document on the file system? The javax.swing.text.html.HTMLDocument class doesn't override the toString() method and getText() removes tags.

Nick Rippe
  • 6,465
  • 14
  • 30
0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65

3 Answers3

2

Use the HTMLEditorKit.write() method.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    Just to point out that HTMLEditorKit's write() has a glitch whereby the last empty paragraph in the document is removed. Fortunately, Stanislav published a fix here: http://java-sl.com/tip_html_kit_last_empty_par.html. Enjoy! – HQCasanova Nov 03 '13 at 18:49
2

That's all what I exactly needed: kit.write(fos, doc, 0, doc.getLength());

0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65
1

I guess this post is very similar to your question:Get String from HTMLDocument

Then write the String to a File. There are many different methods to do this. Take a look at Write String to File.

Community
  • 1
  • 1
snrlx
  • 4,987
  • 2
  • 27
  • 34