使用 ProcessBuilder 启动 CMD [英] Start CMD by using ProcessBuilder

查看:99
本文介绍了使用 ProcessBuilder 启动 CMD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码在 Windows 中启动 CMD 应用程序,但它没有按预期工作.来自不同网站的几个示例表明,cmd"作为 ProcessBuilder 构造中的参数应该可以工作.

I am trying to start the CMD application in windows by using the following code, but it doesn't work as expected. Several examples from different websites shows that "cmd" as an argument in the ProcessBuilder construct should work.

我需要做什么才能让我的 Java 应用程序在 Windows 中打开 CMD 应用程序?

What do I have to do to make my Java app open the CMD application in windows?

 public class JavaTest
 {
     public static void main(String[] args) 
     {
         ProcessBuilder pb = new ProcessBuilder("cmd");

         try 
         {
             pb.start();
             System.out.println("cmd started");
         } 
         catch (IOException e) 
         {
             System.out.println(e.getMessage());
         }  
     }
 }

当我尝试使用一个不存在的应用程序时,它实际上会打印出一个错误,这意味着它实际上运行的是CMD".但是CMD应用没有按预期弹出?

When I try to use a non-existing application it actually prints out an error, so that means it actually runs "CMD". But the CMD application doesn't pop up as expected?

推荐答案

您需要使用 start 命令.实际上,即使我没有看到新的命令提示符弹出,但您可以使用 任务管理器 检查是否确实启动了一个新的 cmd.exe.

You need to use the start command. Actually, even I don't see a new command prompt popping up, but you can check that a new cmd.exe is definitely started using your task manager.

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "start");

不过,使用 Runtime.exec() 可以实现相同的功能,这实际上会弹出一个新的命令提示符.

Though, the same functionality can be achieved using Runtime.exec(), and this actually pops up a new command prompt.

Runtime.getRuntime().exec("cmd.exe /C start");

这篇关于使用 ProcessBuilder 启动 CMD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆