문제

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);
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top