gpt4 book ai didi

javax.swing.text.rtf.RTFEditorKit/RTF 是一种 8 位格式

转载 作者:行者123 更新时间:2023-12-01 07:29:34 26 4
gpt4 key购买 nike

我需要一个简单的 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

我做错了什么?在这种情况下,谷歌不是我的 friend ,我希望你能帮助我:)

最佳答案

RTF是一种 8 位格式,但您要将内容发送到 Writer,这是一个“用于写入字符流的类”。尝试采用 ByteArrayOutputStreamwrite() 变体:

ByteArrayOutputStream baos = new ByteArrayOutputStream();

rtfEditorKit.write(baos, htmlDoc, 0, htmlDoc.getLength());

System.out.println(baos.toString());

控制台:

{\rtf1\ansi{\fonttbl\f0\fnil Monospaced;}\parMy First HeadingMy first paragraph.\par}

关于javax.swing.text.rtf.RTFEditorKit/RTF 是一种 8 位格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19188447/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com