Java JTextPane RTF Save

2019-05-10 00:29发布

问题:

i have the following code trying to save the contents of a JTextPane as RTF. although a file is created in the following code but it is empty!

any tips regarding what am i doing wrong? (as usual dont forget im a beginner!)

if (option == JFileChooser.APPROVE_OPTION) {
////////////////////////////////////////////////////////////////////////
//System.out.println(chooser.getSelectedFile().getName());

//System.out.println(chooser.getSelectedFile().getAbsoluteFile());
///////////////////////////////////////////////////////////////////////////

StyledDocument doc = (StyledDocument)textPaneHistory.getDocument();
RTFEditorKit kit = new RTFEditorKit();

BufferedOutputStream out;

try {
     out = new BufferedOutputStream(new FileOutputStream(chooser.getSelectedFile().getName()));

     kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
} catch (FileNotFoundException e) {
} catch (IOException e){
} catch (BadLocationException e){
}
}

EDIT: HTMLEditorKit if i use HTMLEditorKit it works and thats what i really wanted. SOLVED!

回答1:

            if (textPaneHistory.getText().length() > 0){

            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);

            int option = chooser.showSaveDialog(ChatGUI.this);

            if (option == JFileChooser.APPROVE_OPTION) {

                StyledDocument doc = (StyledDocument)textPaneHistory.getDocument();

                HTMLEditorKit kit = new HTMLEditorKit();

                BufferedOutputStream out;

                try {
                    out = new BufferedOutputStream(new FileOutputStream(chooser.getSelectedFile().getAbsoluteFile()));

                    kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());

                } catch (FileNotFoundException e) {

                } catch (IOException e){

                } catch (BadLocationException e){

                }
            }
        }

here is the solution. it works if HTMLEditorKit is used.



回答2:

Here is a solution for RTF and not HTML.

As RTF is not standardized, I needed some additional tags like \sb and \sa to force my Wordpad to display the file properly.

protected void exportToRtf() throws IOException, BadLocationException {
    final StringWriter out = new StringWriter();
    Document doc = textPane.getDocument();
    RTFEditorKit kit = new RTFEditorKit();
    kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
    out.close();

    String rtfContent = out.toString();
    {
    // replace "Monospaced" by a well-known monospace font
    rtfContent = rtfContent.replaceAll("Monospaced", "Courier New");
    final StringBuffer rtfContentBuffer = new StringBuffer(rtfContent);
    final int endProlog = rtfContentBuffer.indexOf("\n\n");
    // set a good Line Space and no Space Before or Space After each paragraph
    rtfContentBuffer.insert(endProlog, "\n\\sl240");
    rtfContentBuffer.insert(endProlog, "\n\\sb0\\sa0");
    rtfContent = rtfContentBuffer.toString();
    }

    final File file = new File("c:\\temp\\test.rtf");
    final FileOutputStream fos = new FileOutputStream(file);
    fos.write(rtfContent.toString().getBytes());
    fos.close();
}


回答3:

This is how I did when I faced the same problem.

    public void actionPerformed(ActionEvent e) {

        text = textPane.getText();
        JFileChooser saveFile = new JFileChooser();
        int option = saveFile.showSaveDialog(null);
        saveFile.setDialogTitle("Save the file...");

        if (option == JFileChooser.APPROVE_OPTION) {

            File file = saveFile.getSelectedFile();
            if (!file.exists()) {

                try {
                    BufferedWriter writer = new BufferedWriter(
                            new FileWriter(file.getAbsolutePath() + ".rtf"));
                    writer.write(text);
                    writer.close();

                } catch (IOException ex) {

                    ex.printStackTrace();
                    System.out.println(ex.getMessage());
                    JOptionPane.showMessageDialog(null,
                            "Failed to save the file");
                }

            }

            else if (file.exists()) {

                int confirm = JOptionPane.showConfirmDialog(null,
                        "File exists do you want to save anyway?");
                if (confirm == 0) {

                    try {
                        BufferedWriter writer = new BufferedWriter(
                                new FileWriter(file.getAbsolutePath()
                                        + ".rtf"));
                        writer.write(text);
                        writer.close();

                    } catch (IOException ex) {

                        ex.printStackTrace();
                        System.out.println(ex.getMessage());
                        JOptionPane.showMessageDialog(null,
                                "Failed to save the file");
                    }

                }

                else if (confirm == 1) {

                    JOptionPane.showMessageDialog(null,
                            "The file was not saved.");

                }

            }

        }

        if (option == JFileChooser.CANCEL_OPTION) {

            saveFile.setVisible(false);

        }

    }// End of method


回答4:

The only problem I've seen in your code is that you're not closing the output stream (when content is actually written to disk).

Try out.close().

It should solve your problem.