如何使用一些参数从Java调用.exe文件
我需要调用cowsay.exe(这个程序使用符号 绘制动物)并执行命令:cowsay“hello”。如何将“hello”作为参数传递如何使用一些参数从Java调用.exe文件,java,Java,我需要调用cowsay.exe(这个程序使用符号 绘制动物)并执行命令:cowsay“hello”。如何将“hello”作为参数传递 public class cowsay { public static void main(String[] args) throws IOException { Process process = new ProcessBuilder("D:\\cowsay.exe","cowsay Hello").start(); In
public class cowsay {
public static void main(String[] args) throws IOException {
Process process = new ProcessBuilder("D:\\cowsay.exe","cowsay Hello").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
您可以使用java.lang.Runtime类:
public class cowsay {
public static void main(String[] args) throws IOException {
Process process =
Runtime.getRuntime().exec("cowsay hello");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
正如Fungucide指出的,您可以使用RunTime类。但是,我建议您使用将参数作为数组接受的方法。 示例代码:
public static void main(String[] args) {
Try{
String[] command={"D:\\cowsay.exe","cowsay","Hello"};
Runtime.getRuntime().exec(command);
}catch(Exception e){System.out.println(e.getMessage());}
}
这是如果您想将“cowsay”作为参数。如果您只想将“hello”作为参数,请执行以下操作:
public static void main(String[] args) {
Try{
String[] command={"D:\\cowsay.exe","Hello"};
Runtime.getRuntime().exec(command);
}catch(Exception e){System.out.println(e.getMessage());}
}
上面的代码正在执行命令D:\cowsay.exe“cowsay hello”。