Question

I need to get the console output of a JAR file in my GUI application. Im running the JAR calling the command line from my GUI application, as you can see below:

String cmdLine = "java -jar myjar.jar";
myProcess = Runtime.getRuntime().exec(cmdLine);
BufferedReader input = new BufferedReader(new InputStreamReader(myProcess.getInputStream()));
while ((line = input.readLine()) != null) { //do something }

In myjar.JAR, I created a CustomPrintStream in order to log everything to a txt file AND the console. Here it is:

public class CustomPrintStream extends PrintStream
{
static private FileHandler fileTxt;

Logger logger;

public CustomPrintStream()
{
    super(new ByteArrayOutputStream());

    try
    {
        this.logger = Logger.getLogger("LOGGER");
        this.logger.setLevel(Level.INFO);
        fileTxt = new FileHandler("Logging.txt");
    }
    catch (Exception ex)
    {
        // do nothing!
    }

    CustomRecordFormatter formatter = new CustomRecordFormatter();
    this.fileTxt.setFormatter(formatter);
    this.logger.addHandler(fileTxt);

    ConsoleHandler ch = new ConsoleHandler();
    ch.setFormatter(formatter);
    logger.addHandler(ch);

    logger.setUseParentHandlers(false);
}

@Override
public void print(String s)
{
    super.print(s);
    logger.info(s);
}
}

Also, I set the standard output of myjar.JAR to the custom stream:

System.setOut(CustomPrintStream);

Running the JAR file in windows command line works fine, but when I try to get console output programmatically in my GUI application it just doesn't work.

Does anyone know the solution?

Was it helpful?

Solution

GUI applications doesn't have a "console". Why don't you try instead adding the jar as a reference to your GUI project and call the right function programatically?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top