I'm using a StyleDocument to display my content in a JTextPane. I searched for a while and saw that I can write with the HTMLEditorKit the document I get from the textpane to a file. But when I want to read this file with the HTMLEditorKit it doesn't parse in the right document. I get two different results:
Saving:
Document doc = textpane.getStyledDocument();
HTMLEditorKit kit = new HTMLEditorKit();
kit.write(new FileOutputStream("path"), doc, 0, doc.getLength());
Loading (2 versions):
HTMLEditorKit kit = new HTMLEditorKit();
Document doc = null;
Document doc2 = kit.createDefaultDocument();
kit.read(new FileInputStream("path"), doc, 0);
kit.read(new FileInputStream("path"), doc2, 0);
textpane.setDocument(doc);
textpane.setDocument(doc2);
When you initialize your JTextPane add the following line: textpane.setContentType("text/html");
Change Saving to look like this:
Document document = textpane.getStyledDocument();
EditorKit kit = textpane.getEditorKit();
kit.write(new FileOutputStream(new File("path")), doc, 0, doc.getLength());
Change Loading to look like this:
EditorKit kit = pane2.getEditorKit();
Document doc = kit.createDefaultDocument();
kit.read(new FileInputStream(new File("path")), doc, 0);
textpane.setDocument(doc);
Using this setup in my test environment I was able to set the text in a JTextPane
to some html, get the html from the pane, write it to a file and subsequently read it back from that same file. I didn't see any reason to use a HTMLEditorKit
as you are not doing anything html specific however you can change that as you see fit.