简体   繁体   English

Java System.out重定向问题

[英]Java System.out redirect issue

I've written an recursive directory search that, for each dir that matches a certain pattern, will execute a .bat. 我编写了一个递归目录搜索,对于与特定模式匹配的每个目录,将执行一个.bat。 Now I want to redirect messages printed to the java console (no need to write standardErr) to an JTextArea. 现在,我想将打印到Java控制台的消息重定向到JTextArea(无需编写standardErr)。 The following code is for the redirection part of the GUI. 以下代码用于GUI的重定向部分。

taConsole = new JTextArea();
taConsole.setEditable(false);
PrintStream printStream = new PrintStream(new CustomOutputStream(taConsole));
JScrollPane consolePane= new JScrollPane(taConsole);
System.setOut(printStream);

The recursive search and process execution is ok, but when I try to execute with GUI nothing is written on the textarea. 递归搜索和流程执行是可以的,但是当我尝试使用GUI执行时,没有任何文字写入文本区域。 When I inserted some System.out.println("foobar") into the GUI class, the messages were printed into the text area as expected. 当我将某些System.out.println(“ foobar”)插入GUI类时,消息将按预期方式打印到文本区域中。 However the prints on my logic class are not being inserted into the textarea. 但是,我的逻辑类上的打印没有插入到textarea中。

The program prints a message before and after the bat execution, as follows: 该程序在执行bat之前和之后打印一条消息,如下所示:

System.out.println("Generating PDFs for"+grandparent+"\\"+parent+"\\ ..."+f.getName());
Process p = Runtime.getRuntime().exec("cmd /c start /wait .\\Run.bat \""+f.getParent()+"\"");
p.waitFor();
System.out.println("PDFs generated!");

The (not so) funny thing is that, when i remove the "start" statement from the command line, the messages are printed in the textarea as I want, but the process is not executed. (不是这样)有趣的是,当我从命令行中删除“ start”语句时,消息将按我的意愿打印在文本区域中,但是该过程未执行。 With the start statement, the program executes and generates my pdfs normally, but no messages are printed to text area at all. 使用start语句,程序可以正常执行并生成我的pdf,但是根本没有消息打印到文本区域。

What am I missing here? 我在这里想念什么?

Thanks in advance. 提前致谢。

SOLVED: 解决了:

the actual problem was that the main thread for the swing GUI was getting blocked waiting for the recursive search (and PDF generating) to end, so the frame wasn't being refreshed. 实际的问题是,swing GUI的主线程被阻塞,等待递归搜索(和PDF生成)结束,因此未刷新框架。 Solved by implementing Runnable on the logic class and calling it through a new thread in the GUI. 通过在逻辑类上实现Runnable并通过GUI中的新线程调用它来解决。

try 尝试

new PrintStream(new CustomOutputStream(taConsole), true);

or flush after every println 或每次printlnflush

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM