Java ProcessBuilder showing console of started java application?

孤者浪人 提交于 2019-12-10 11:14:15

问题


I have a JAVA application that launches (using ProcessBuilder) another JAVA application like this:

String val = "something";
ProcessBuilder processBuilder = new ProcessBuilder("java", "-classpath", dir, appName, val);
Process p = processBuilder.start();

Now, this works fine, appName is launched with the parameter val and it runs and works ... great ... the problem is no Console Window appears ... appName does a LOT of outputting to the console and we need to see it ... how can I start the process with a console?

I am trying stuff like ("CMD.exe", "java", "-classpath", dir, appName, val), etc... but I can't get it right ...

Also, I can't redirect the streams, my program can actually start 5-10 of these appName's, each should have their own console window showing their own information.

Any help would be much appreciated. Thanks,


回答1:


console windows are generally not the most reliable form of logging. they only store a set amount of information (buffer) and can behave differently across platforms.

i strongly suggest logging to a file using something like log4j and if you need to see it real time use a tail like program (i see you're using windows).

in addition to this, seeing as you want the windows visible at all times and launching a tail program for each log might be annoying, i'd write my own log window in java swing.

the basic idea is to not rely on the OS too much.




回答2:


Tried Runtime.getRuntime().exec("cscript java -classpath ..."); ?

Anyway, consider using a logging framwork (log4j, commons-logging), because opening 5 consoles is not the most clever thing to do.




回答3:


I call a few shell scripts via Process to open a command line window and launch whatever I need. As long as the scripts don't detach - you can usually stop any shell command from doing this -java will still hold the running process.

I did it in linux but the concept should be similar.

#!/bin/bash
# To open a process in a new window.
gnome-terminal -x ./your-real-shell-script-here.sh "$@"

the real script will have your java execution in it, such as:

#!/bin/bash
java -jar your-jar-file.jar "$@"

I think you can use javaw to run on windows, so you might only need the one shell script.




回答4:


A Console object only exists when you execute java.... from a console. Otherwise, the call to obtain one returns null.

If you want to see a console, you need to open a command shell console (e.g. windows cmd.exe or Unix bash shell window) and type:

java -classpath="..." com.example.appName arg1

If you want to run in a different manner, sorry to say, logging to Console is not for you. Instead, log using one of:

  • log4j
  • slf4j
  • logback


来源:https://stackoverflow.com/questions/1876883/java-processbuilder-showing-console-of-started-java-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!