英文:
Java 8: how to convert plain UTF-8 text into RTF (with symbols > 127)?
问题
我找到了许多关于如何使用RTFEditorKit将RTF转换为纯文本的方法,但没有找到关于如何将纯文本转换为RTF的方法。
我不想手动进行操作,因为在我的情况下,我们必须将所有大于128的字符转换为十六进制字符串,以获得正确的RTF文件。我希望能够借助一些库来实现这一点。
我正在尝试使用RTFEditorKit进行操作:
String orig = "Hello Привет こんにちは";
InputStream is = new ByteArrayInputStream(orig.getBytes(StandardCharsets.UTF_8));
// String tmpStr = is.getText("UTF-8"); // 这里是正确的tmpStr
RTFEditorKit rtfParser = new RTFEditorKit();
javax.swing.text.Document doc = rtfParser.createDefaultDocument();
rtfParser.read(is, doc, 0);
int docLen = doc.getLength(); // !!! 这里的docLen = 0
OutputStream os = new ByteArrayOutputStream();
rtfParser.write(os, doc, 0, docLen, );
但无法将纯文本读入Document对象中。
英文:
I've found many "how to RTF -> plain text" with RTFEditorKit, but no one "plain->rtf".
I wouldn't to do it manually, because in my case we have to convert all chars over than 128 to hex strings to get correct RTF file. I would want to do it with some library.
I'm trying to do it with RTFEditorKit:
String orig = "Hello Привет こんにちは";
InputStream is = new ByteArrayInputStream(orig.getBytes(StandardCharsets.UTF_8));
// String tmpStr = is.getText("UTF-8"); // here is correct tmpStr
RTFEditorKit rtfParser = new RTFEditorKit();
javax.swing.text.Document doc = rtfParser.createDefaultDocument();
rtfParser.read(is, doc, 0);
int docLen = doc.getLength(); // !!! here is docLen = 0
OutputStream os = new ByteArrayOutputStream();
rtfParser.write(os, doc, 0, docLen, );
But cannot read plain text into Document object.
答案1
得分: 1
这段代码对我有效,尽管我不确定能否准确定位问题所在。我将字符串插入 Document
中:
String orig = "Hello Привет こんにちは";
RTFEditorKit rtfParser = new RTFEditorKit();
javax.swing.text.Document doc = rtfParser.createDefaultDocument();
doc.insertString(0, orig, null);
int docLen = doc.getLength();
OutputStream os = Files.newOutputStream(Paths.get("test.rtf"), StandardOpenOption.CREATE);
rtfParser.write(os, doc, 0, docLen);
英文:
I am not sure I can pinpoint where things are going wrong in your code but this works for me. I insert the string into the Document
:
String orig = "Hello Привет こんにちは";
RTFEditorKit rtfParser = new RTFEditorKit();
javax.swing.text.Document doc = rtfParser.createDefaultDocument();
doc.insertString(0, orig, null);
int docLen = doc.getLength();
OutputStream os = Files.newOutputStream(Paths.get("test.rtf"), StandardOpenOption.CREATE);
rtfParser.write(os, doc, 0, docLen);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论