我需要调用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();
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);
}
}
答案 0 :(得分:4)
您使用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);
}
}
}
答案 1 :(得分:0)
正如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());}
}