首先要着重声明的是:我需要显示DOS窗口,而不是隐藏,因为我需要实时的看到输出的内容
比如我要连续执行下面的命令:
dir
ping 192.168.1.1
ping 192.168.1.2
ping 192.168.1.3
ver我是这样写的: Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.StandardInput.WriteLine("dir");
p.StandardInput.WriteLine("ping 192.168.1.1");
p.StandardInput.WriteLine("ping 192.168.1.2");
p.StandardInput.WriteLine("ping 192.168.1.3");
p.StandardInput.WriteLine("ver");但是在DOS窗口看不到输出。而如果不用命令行重定向,就没法执行多个命令。
而如果每个命令都调用Process.Start方法,显示的内容又在不同的窗口了
比如我要连续执行下面的命令:
dir
ping 192.168.1.1
ping 192.168.1.2
ping 192.168.1.3
ver我是这样写的: Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.StandardInput.WriteLine("dir");
p.StandardInput.WriteLine("ping 192.168.1.1");
p.StandardInput.WriteLine("ping 192.168.1.2");
p.StandardInput.WriteLine("ping 192.168.1.3");
p.StandardInput.WriteLine("ver");但是在DOS窗口看不到输出。而如果不用命令行重定向,就没法执行多个命令。
而如果每个命令都调用Process.Start方法,显示的内容又在不同的窗口了
写完之后,开个线程执行这个bat文件,应该命令窗口可以出现
楼主可以试试
import java.io.*;
public class Hello { public static void main(String[] args) {
try { Process p=Runtime.getRuntime().exec("cmd");
OutputStream os=p.getOutputStream();
OutputStreamWriter ow=new OutputStreamWriter(os); BufferedWriter bw=new BufferedWriter(ow);
bw.write("dir");
bw.newLine();
bw.flush();
bw.close();
BufferedReader buffer = new BufferedReader(new InputStreamReader(p.getInputStream()));
for (String line = buffer.readLine(); line != null; line = buffer.readLine())
{
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
你干脆用C++的system("..")算了,更方便