我需要调用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);
}
}发布于 2015-11-13 05:24:19
您可以使用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);
}
}
}发布于 2015-11-13 17:33:29
正如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“作为参数的话。如果你想要“d=only”作为参数,那么你可以这样做:
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());}
}https://stackoverflow.com/questions/33681500
复制相似问题