我有一个从 .bat 文件运行的 Java .jar 应用程序,以便将参数传递给 Java 应用程序。该应用程序打开一个控制台(确切地说是cmd.exe),定期向其中写入内容并接受一些命令。我正在尝试在 C# Winforms 中创建一种围绕它的包装器以简化它的使用。如何使用与 .bat 文件中相同的参数运行 .jar、捕获实时输出并编写执行命令?
最佳答案
是的,可以使用System.Diagnostics.Process class来做到这一点和 ProcessStartInfo class来自 .NET 框架。 Process 类用于控制(启动/停止)所需的进程(应用程序),ProcessStartInfo 类用于配置将启动的流程实例(参数、重定向输入和输出、显示/隐藏进程窗口等)。
启动 jar 文件的代码如下所示:
var jarFile = "D:\\software\\java2html\\java2html.jar");
// location of the java.exe binary used to start the jar file
var javaExecutable = "c:\\Program Files (x86)\\Java\\jre7\\bin\\java.exe";
try
{
// command line for java.exe in order to start a jar file: java -jar jar_file
var arguments = String.Format(" -jar {0}", jarFile);
// create a process instance
var process = new Process();
// and instruct it to start java with the given parameters
var processStartInfo = new ProcessStartInfo(javaExecutable, arguments);
process.StartInfo = processStartInfo;
// start the process
process.Start();
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
通常的方式start a jar file是:
java -jar file.jar
可以肯定的是,该进程将找到可执行文件(在本例中为 java),最好指定要启动的进程的完全限定路径。
为了重定向您正在启动的应用程序的标准输出,您需要设置ProcessStartInfo.RedirectStandardOutput property为 true
,然后使用 Process.StandardOutput property stream获取已启动应用程序的输出。上面示例中的应用程序修改后的代码如下所示:
// command line for java.exe in order to start a jar file: java -jar jar_file
var arguments = String.Format(" -jar {0}", jarFile);
// indicate, that you want to capture the application output
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
// create a process instance
var process = new Process();
// and instruct it to start java with the given parameters
var processStartInfo = new ProcessStartInfo(javaExecutable, arguments);
process.StartInfo = processStartInfo;
// start the process
process.Start();
// read the output from the started appplication
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
如果您也想控制输入,请设置 ProcessStartInfo.RedirectStandarInput property为 true
,然后使用 Process.StandardInput property stream将输入数据发送到启动的应用程序。
关于c# - 如何使用参数打开外部 Java 控制台应用程序、捕获输出并在其上执行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22870898/