0

HTML2RTF 用のシンプルなコンバーターが必要で、フォロー コードを実行しようとしましたが、このコード例でエラーが発生しました。

コード:

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.rtf.RTFEditorKit;

public class converter {
    private static Pattern htmlTrimPattern = Pattern.compile(".*<body>(.*)</body>.*", Pattern.DOTALL);

    public static void main(String[] args)
    {


        toRtf("<!DOCTYPE html>\n" +
                "<html>\n" +
                "<body>\n" +
                "\n" +
                "<h1>My First Heading</h1>\n" +
                "\n" +
                "<p>My first paragraph.</p>\n" +
                "\n" +
                "</body>\n" +
                "</html>\n");

    }

    public static String toRtf(String html) {
        ByteArrayInputStream input= new ByteArrayInputStream(html.getBytes());
        StringWriter writer = new StringWriter();
        try {
            RTFEditorKit rtfEditorKit = new RTFEditorKit();
            HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
            Document htmlDoc = htmlEditorKit.createDefaultDocument();
            htmlEditorKit.read(input, htmlDoc, 0);
            rtfEditorKit.write(writer, htmlDoc, 0, htmlDoc.getLength());
        } catch (Exception ex) {
            System.out.println("Error"+ex);
        }
        System.out.println(writer.toString());
        return writer.toString();
    }
}

エラー:

Errorjava.io.IOException: RTF is an 8-bit format

私は何を間違っていますか?この場合、グーグルは私の友人ではありません。あなたが私を助けてくれることを願っています:)

4

1 に答える 1

7

RTFは 8 ビット形式ですWriterが、「文字ストリームに書き込むためのクラス」である にコンテンツを送信しています。のバリエーションを試してwrite()くださいByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
…
rtfEditorKit.write(baos, htmlDoc, 0, htmlDoc.getLength());
…
System.out.println(baos.toString());

コンソール:

{\rtf1\ansi
{\fonttbl\f0\fnil 等幅;}

\パー
My First HeadingMy 最初の段落。\par
}
于 2013-10-04T23:43:00.043 に答える