gpt4 book ai didi

java - java中读取RTF文件时如何设置格式?

转载 作者:太空宇宙 更新时间:2023-11-04 15:06:50 25 4
gpt4 key购买 nike

我需要用Java读取一些RTF文件。所以我得到了一个最初运行良好的代码。但我的问题是:读取这些文件时是否可以设置格式(例如:UTF-8、UTF-16 等)?

这里我发布了读取 RTF 文件的代码:

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;
}

最佳答案

我相信FileReader正在使用默认编码。幸运的是,read() 方法也被重载来处理流 - 对于它们,您可以设置要使用的编码:

rtfKit.read(new FileInputStream(fileDir), StandardCharsets.UTF_8), ...)

关于java - java中读取RTF文件时如何设置格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21872808/

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