0

I am writing a program that uses jtidy to clean up html from source code obtained from a URL. I want to display the errors and warnings in a GUI, in a JTextArea. How would I "reroute" the warnings from printing to stdout to the JTextArea? I've looked over the Jtidy API and don't see anything that does what I want. Anyone know how I can do this, or if it's even possible?

// testing jtidy options

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);
}
kleopatra
  • 51,061
  • 28
  • 99
  • 211
cHam
  • 2,624
  • 7
  • 26
  • 28

1 Answers1

1

Assuming JTidy prints errors and warnings to stdout, you can just 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);

There is an analogous method if you need to do this for System.err instead/as well.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • I tried, but the "StandardCharsets.UTF_8" part gives me an error and only the option to create a class with that name (in eclipse) do I need to import something, or is there a minor typo there? – cHam Nov 08 '12 at 04:56
  • It's part of Java 7. If you're not there yet, you can get by well enough omitting the charset argument entirely, though it's not best practice. Otherwise, pass `Charset.forName("UTF-8")` and catch the exception (which will never actually be thrown, in practice). See also http://stackoverflow.com/questions/1684040/java-why-charset-names-are-not-constants – Matt Ball Nov 08 '12 at 05:16