Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get output of a java application C#

Tags:

java

c#

This may be hard to understand, but I want to get the output of a java application in a console C# app.

When you start a java application with Process.Start in a C# console app, the java application takes control, and all lines are written using System.Out.Println().

I want to start a java application, make it so System.out.println() gets stored in a variable and not printed, and then reprint what the variable is with Console.WriteLine()

Allow me to rephrase. #1 Start java app in c# console app with process.start. #2 Cancel java's attempts to output what it was going to output with System.out.prinln(), and instead store it in a variable/string. #3 reprint that string using Console.WriteLine().

Redirecting standard output does not work for this.

If you are wondering, this is for minecraft bukkit.

like image 705
halpme142 Avatar asked Mar 05 '26 02:03

halpme142


1 Answers

Java application:

public class JavaApplication {

    public static void main(String[] args) {
        System.out.println("Java application outputs something into stdout");
        System.err.println("Java application outputs something into stderr");
    }
}

C# application

using System;
using System.Diagnostics;

namespace CaptureProcessStdOutErr
{
  public class Program
  {
    public static void Main(string[] args)
    {
      var startInfo = new ProcessStartInfo("java", "JavaApplication") // proper path to java, main java class, classpath, jvm parameters, etc must be specified or use java -jar jarName.jar if packaged into a single jar
      {
        RedirectStandardError  = true,
        RedirectStandardOutput = true,
        UseShellExecute        = false
      };

      var process = Process.Start(startInfo);

      process.WaitForExit();

      Console.WriteLine("Captured stderr from java process:");
      Console.WriteLine(process.StandardError.ReadToEnd());
      Console.WriteLine();
      Console.WriteLine("Captured stdout from java process");
      Console.WriteLine(process.StandardOutput.ReadToEnd());
    }
  }
}

This assumes java.exe is in the PATH.

Compile JavaApplication and put JavaApplication.class file next to C# application (CaptureProcessStdOutErr.exe)

run CaptureProcessStdOutErr.exe

Output:

Captured stderr from java process:
Java application outputs something into stderr

Captured stdout from java process
Java application outputs something into stdout
like image 114
Nick Y Avatar answered Mar 07 '26 16:03

Nick Y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!