I have a C# program that needs to execute a Java program, however, when executing Java applications, no output is shown. I would also need this output to be live, as well as input.
Take this sample code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Executing \"echo test\":");
EchoRedirectDemo();
Console.WriteLine("Executing \"java -version\":");
JavaRedirectDemo();
}
static void JavaRedirectDemo()
{
ProcessStartInfo processStartInfo = new ProcessStartInfo("java")
{
Arguments = "-version",
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true
};
Process process = Process.Start(processStartInfo);
process.WaitForExit();
Console.WriteLine(process.StandardOutput.ReadToEnd());
}
static void EchoRedirectDemo()
{
ProcessStartInfo processStartInfo = new ProcessStartInfo("echo")
{
Arguments = "test",
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true
};
Process process = Process.Start(processStartInfo);
process.WaitForExit();
Console.WriteLine(process.StandardOutput.ReadToEnd());
}
}
It will run echo test
just fine and redirect the in/out/err, but there will be no in/out/err on the java -v
command, as seen below:
Executing "echo test":
test
Executing "java -version":
Any idea about how to fix this issue?
CodePudding user response:
java -version
will output the version info on STDERR, not STDOUT. This would require you to use something like Console.WriteLine(process.StandardError.ReadToEnd());
in your C# program.
However, java --version
(note the double dash) output the version info on STDOUT. Thus, i would recommend to use this instead of java -version
.
(This is also described in Java's online documentation about the commandline parameters at https://docs.oracle.com/en/java/javase/13/docs/specs/man/java.html)
CodePudding user response:
CliWrap can simplify this for you.
using System.Text;
using System;
using CliWrap;
using System.Threading.Tasks;
namespace proj
{
public class Program
{
public static async Task Main(string[] args)
{
var stdOutBuffer = new StringBuilder();
var stdErrBuffer = new StringBuilder();
var result = await Cli.Wrap("java")
.WithArguments("-version")
.WithWorkingDirectory("/")
.WithStandardOutputPipe(PipeTarget.ToStringBuilder(stdOutBuffer))
.WithStandardErrorPipe(PipeTarget.ToStringBuilder(stdErrBuffer))
.ExecuteAsync();
var stdOut = stdOutBuffer.ToString();
var stdErr = stdErrBuffer.ToString();
Console.WriteLine(stdOut);
Console.WriteLine(stdErr);
}
}
}
OUTPUT
java version "1.8.0_301"
Java(TM) SE Runtime Environment (build 1.8.0_301-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.301-b09, mixed mode)