我需要以编程方式打开一个控制台(在Windows中),然后我需要在刚刚创建的控制台中执行一个大命令。我试着写输出流但没有运气。这是我到目前为止提供控制台的代码。
File fileOne = new File(args[0]);
String[] command = { "cmd", "/c", "Start"};
ProcessBuilder procBuilder = new ProcessBuilder(command);
procBuilder.directory(fileOne);
答案 0 :(得分:1)
这应该有效
你需要像
这样的东西String[] command =
{
"cmd",
};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("dir c:\\ /A /Q");
// write any other commands you want here
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
SyncPipe类:
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
答案 1 :(得分:1)
以下是我用于为程序创建启动图标的示例。
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c cd \""+"c:\\CombineImages\\"+"\" & start cmd.exe /k \"java -Xms1G -Xmx1G jar CombineImages.jar\"");
将该代码放在main方法中,并替换为您要运行的任何命令。