c# - 如何使用参数打开外部 Java 控制台应用程序、捕获输出并在其上执行命令?

标签 c# java winforms batch-file

我有一个从 .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 propertytrue,然后使用 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 propertytrue,然后使用 Process.StandardInput property stream将输入数据发送到启动的应用程序。

关于c# - 如何使用参数打开外部 Java 控制台应用程序、捕获输出并在其上执行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22870898/

相关文章:

c# - 使用正则表达式查找字符串中的所有匹配项

java - "Next bigger number with the same digits"- 执行超时(16000 毫秒)- Codewars

C# 夏令时 DateTime 开关

java - 为什么 Windows 不让 mod_authnz_external 调用的程序使用网络?

c# - 不允许循环文件引用。发布 ASP.NET (2.0) 网站

java - 迭代器返回一个对象,而不是所需的对象

java - 让 AlertDialog 等待用户输入?

c# - 向其他用户或所有登录用户显示 C# 窗体

c# - 为什么 date.ToString() 随时间显示

c# - 在 C# 中将项目添加到 ListView 太慢