2012-11-08 30 views
0

警告消息我写一个使用jtidy清理从一个URL获得源代码的html的程序。我想在GUI中显示错误和警告,在JTextArea中。我将如何将打印到stdout的警告“重新路由”到JTextArea?我查看了Jtidy API,没有看到任何我想要的东西。任何人都知道我能做到这一点,或者甚至有可能吗?显示Jtidy错误/ GUI中的JTextArea

//测试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); 
} 

回答

1

假设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); 

an analogous method,如果你需要为System.err做到这一点,而不是/以及。

+0

我试过了,但“StandardCharsets.UTF_8”一部分给我一个错误,只创建一个类使用该名称(在Eclipse)的选项,我需要进口的东西,还是有一个小错字吗? – cHam

+0

它是Java 7的一部分。如果你还没有,你可以完全忽略charset参数,尽管这不是最佳实践。否则,传递'Charset.forName(“UTF-8”)'并捕获异常(实际上它将永远不会抛出)。另见http://stackoverflow.com/questions/1684040/java-why-charset-names-are-not-constants –