Reputation: 349
I need to read some RTF files in Java .So i got a code which worked fine initially . But my question is that : Is it possible to set format (Eg: UTF-8 ,UTF-16,etc) while reading these files ?
Here i have posted the code which reads RTF file :
public static String rtf_read(String fileName) throws Exception, BadLocationException
{
JEditorPane p = new JEditorPane();
p.setContentType("text/rtf");
EditorKit rtfKit = p.getEditorKitForContentType("text/rtf");
rtfKit.read(new FileReader(fileName), p.getDocument(), 1);
rtfKit = null;
// convert to text
EditorKit txtKit = p.getEditorKitForContentType("text/plain");
Writer writer = new StringWriter();
txtKit.write(writer, p.getDocument(), 0, p.getDocument().getLength());
String documentText = writer.toString();
return documentText;
}
Upvotes: 2
Views: 1385
Reputation: 9
It works for me with the following lines of code:
FileInputStream is = new FileInputStream(rtfFilePath);
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader buffReader = new BufferedReader(isr);
rtfKit.read(buffReader, p.getDocument(), 0);
Upvotes: -1
Reputation: 10606
I believe FileReader
is using the default encoding. Fortunately, the read()
method was overloaded to handle streams as well - and for them, you can set the encoding you want to use:
rtfKit.read(new FileInputStream(fileDir), StandardCharsets.UTF_8), ...)
Upvotes: 0