gpt4 book ai didi

java - doc 到 html 转换后如何在 jeditorepane 中显示 html 文件?

转载 作者:行者123 更新时间:2023-12-01 15:21:49 26 4
gpt4 key购买 nike

我将 doc 文件转换为 html 并在我的 jeditorepane 上显示该 doc 文件。

该程序正在我的管理员帐户上运行。当我在 Windows XP 中使用用户帐户登录时,该文件不会显示。

try
{

File docFile=new File("c:\\159.doc"); // file object was created
FileInputStream finStream=new FileInputStream(docFile.getAbsolutePath());
HWPFDocument doc=new HWPFDocument(finStream);

WordExtractor wordExtract=new WordExtractor(doc);
Document newDocument = DocumentBuilderFactory.newInstance() .newDocumentBuilder().newDocument();
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(newDocument) ;

wordToHtmlConverter.processDocument(doc);

StringWriter stringWriter = new StringWriter();
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" );
transformer.setOutputProperty( OutputKeys.METHOD, "html" );
transformer.transform(
new DOMSource( wordToHtmlConverter.getDocument() ),
new StreamResult( stringWriter ) );

String html = stringWriter.toString();

System.out.println(html);


FileOutputStream fos;
DataOutputStream dos;

File file= new File("C:\\my.html");
fos = new FileOutputStream(file);
dos=new DataOutputStream(fos);
// dos.writeInt();
dos.writeUTF(html);

JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setEditable(false);


editorPane.setPage(file.toURL());

JScrollPane scrollPane = new JScrollPane(editorPane);

JFrame f = new JFrame("O'Reilly & Associates");
// Next line requires Java 1.3
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(scrollPane);
f.setSize(512, 342);
f.setVisible(true);
}catch(Exception e)
{

}

最佳答案

您不应该使用 DataOutputStream 用于编写一个字符串,该字符串已经是您的 HTML 格式,因为这将为您创建一个二进制文件。打开C:\\my.html你就会明白这一点在记事本中。它看起来不像您的常规 HTML 文件,并且很可能以不可打印的字符开头,而不是 <HTML>标签。

您可以使用简单的 FileWriter

File file= new File("C:\\my.html");
FileWriter fw = new FileWriter(file);
fw.write(html);
fw.flush();
fw.close();

编辑:

还建议使用file.toURI().toURL()而不是file.toURL()因为后者是一种已弃用的方法。根据java文档

This method does not automatically escape characters that are illegal in URLs. It is recommended that new code convert an abstract pathname into a URL by first converting it into a URI, via the toURI method, and then converting the URI into a URL via the URI.toURL method.

关于java - doc 到 html 转换后如何在 jeditorepane 中显示 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10793782/

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