我正在编写一个程序,该程序使用jtidy清理从URL获得的源代码中的html。我想在JTextArea的GUI中显示错误和警告。我该如何将警告从打印输出到标准输出,重新发送到JTextArea?我查看了Jtidy API,但没有发现任何符合我想要的功能。有人知道我该怎么做,或者甚至有可能吗?
//测试jtidy选项
public void test(String U) throws MalformedURLException, IOException
{
Tidy tidy = new Tidy();
InputStream URLInputStream = new URL(U).openStream();
File file = new File("test.html");
FileOutputStream fop = new FileOutputStream(file);
tidy.setShowWarnings(true);
tidy.setShowErrors(0);
tidy.setSmartIndent(true);
tidy.setMakeClean(true);
tidy.setXHTML(true);
Document doc = tidy.parseDOM(URLInputStream, fop);
}
最佳答案
假设JTidy将错误和警告输出到stdout,则只需temporarily change where System.out
calls go:
PrintStream originalOut = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream myOutputStream = new PrintStream(baos);
System.setOut(myOutputStream);
// your JTidy code here
String capturedOutput = new String(baos.toByteArray(), StandardCharsets.UTF_8);
System.setOut(originalOut);
// Send capturedOutput to a JTextArea
myTextArea.append(capturedOutput);
如果您需要代替
System.err
来执行此操作,也可以使用an analogous method。