【问题标题】:Displaying Jtidy error/warning messages in a GUI JTextArea在 GUI JTextArea 中显示 Jtidy 错误/警告消息
【发布时间】:2012-11-08 04:22:44
【问题描述】:

我正在编写一个程序,它使用 jtidy 从从 URL 获得的源代码中清理 html。我想在 GUI 中的 JTextArea 中显示错误和警告。我将如何将警告从打印到标准输出“重新路由”到 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);
}

【问题讨论】:

    标签: java swing jtextarea jtidy


    【解决方案1】:

    假设 JTidy 将错误和警告打印到标准输出,您只需 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 来代替/以及。

    【讨论】:

    • 我试过了,但是“StandardCharsets.UTF_8”部分给了我一个错误,只有创建一个具有该名称的类的选项(在 Eclipse 中)我才需要导入一些东西,或者是否有一个未成年人有错别字吗?
    • 它是 Java 7 的一部分。如果您还没有,您可以完全省略 charset 参数,尽管这不是最佳实践。否则,传递Charset.forName("UTF-8") 并捕获异常(实际上永远不会抛出异常)。另见stackoverflow.com/questions/1684040/…
    猜你喜欢
    • 2017-01-08
    • 2011-01-28
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    相关资源
    最近更新 更多