在Java中,我有一个将XML元数据从一种标准转换为另一种标准的软件包。该包最终通过一个函数访问,并通过PrintStream对象发送其所有输出。发送的输出只是每个文件的状态以及它是否被翻译。如果可能,将Java PrintStream中的信息发送到JTextPane的最佳方法是什么?
这是非常非常愉快,如果我只是打印到System.out,但实际上,我希望把它打印出来给JTextPane中而其转换(有点像一个进步文本框)。在翻译XML之后打印状态并不重要,但由于可能有数以千计的XML文件,这是不可行的。
我试过的一件事是使用一个线程,该线程从PrintStream(连接到ByteArrayOutputStream)获取所有信息,并让它将任何新信息发送到文本窗格。不幸的是,这仍然在翻译结束时立即发送所有信息。这确实为System.out正常工作。
下面是做翻译,并试图显示输出代码:
public class ConverterGUI extends javax.swing.JFrame {
boolean printToResultsBox = false;
PrintStream printStream = null;
ByteArrayOutputStream baos = null;
private class ResultsPrinter implements Runnable {
public ResultsPrinter() {
baos = new ByteArrayOutputStream();
printStream = new PrintStream(baos);
}
public void run() {
String tempString = "";
while (printToResultsBox) {
try {
if (!baos.toString().equals(tempString)) {
tempString = baos.toString();
resultsBox.setText(tempString);
}
} catch (Exception ex) {
}
}
}
}
...
ResultsPrinter rp = new ResultsPrinter();
Thread thread = new Thread(rp);
thread.start();
// Do the translation.
try {
printToResultsBox = true;
boolean success = false;
TranslationEngine te = new TranslationEngine();
// fileOrFolderToConvert is a text box in the GUI.
// linkNeeded and destinationFile are just parameters for the translation process.
success = te.translate(fileOrFolderToConvert.getText(), linkNeeded, destinationFile, printStream);
if (success) {
printStream.println("File/folder translation was a success.");
}
resultsBox.setText(baos.toString());
} catch (Exception ex) {
printStream.println("File translation failed.");
} finally {
printToResultsBox = false;
}
...
}
最终,这个代码打印出来的的JTextPane就好毕竟翻译完成,但没有在。有什么建议么?我是否需要将PrintStream更改为其他内容?