考虑以下代码:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyledDocument;
import javax.swing.text.rtf.RTFEditorKit;
public class TestRTF {
public static void main(String args[]) throws BadLocationException, IOException {
new TestRTF();
}
public TestRTF() throws BadLocationException, IOException {
StyledDocument doc = new DefaultStyledDocument();
JTextPane tp = new JTextPane(doc);
doc.insertString(0, "This is a test", null);
RTFEditorKit kit = new RTFEditorKit();
for(int i=0; i<4; i++) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
kit.write(out, doc, 0, doc.getLength());
String s = out.toString();
System.out.println(s);
System.out.println("-------------------");
doc.remove(0, doc.getLength());
kit.read(new ByteArrayInputStream(s.getBytes()), doc, 0);
}
}
}
我希望这会打印出相同的字符串四次,而是在从TextPane读取的循环中,并用读取的内容替换内容导致创建附加段落:
{\rtf1\ansi
{\fonttbl\f0\fnil Monospaced;\f1\fnil Dialog;}
{\colortbl\red0\green0\blue0;\red51\green51\blue51;}
\f1\fs24\i0\b0\cf1 This is a test\par
}
-------------------
{\rtf1\ansi
{\fonttbl\f0\fnil Monospaced;\f1\fnil Dialog;}
{\colortbl\red0\green0\blue0;\red51\green51\blue51;}
\li0\ri0\fi0\f1\fs24\i0\b0\ul0\cf1 This is a test\par
\li0\ri0\fi0\ul0\par
}
-------------------
{\rtf1\ansi
{\fonttbl\f0\fnil Monospaced;\f1\fnil Dialog;}
{\colortbl\red0\green0\blue0;\red51\green51\blue51;}
\li0\ri0\fi0\f1\fs24\i0\b0\ul0\cf1 This is a test\par
\par
\ul0\par
}
-------------------
{\rtf1\ansi
{\fonttbl\f0\fnil Monospaced;\f1\fnil Dialog;}
{\colortbl\red0\green0\blue0;\red51\green51\blue51;}
\li0\ri0\fi0\f1\fs24\i0\b0\ul0\cf1 This is a test\par
\par
\par
\ul0\par
}
-------------------
这是RTFEditorKit中的错误,还是我做错了什么?
答案 0 :(得分:0)
我会在RTFEditorKIt中说出它的错误。
实际上是空的DefaultStyledDocument(在套件中使用)直到最后有一个段落(有一个\ n)。看起来套件并不关心段落,但每次创建新段落而不是使用现有段落。
您可以尝试支持更多内容的the alternative RTF Editor Kit