简体   繁体   English

如何使 Java 在同一命令提示符窗口中打开批处理文件

[英]How to Make Java Open a Batch File in Same Command Prompt Window

I am trying to make a console-based Java application that starts some batch scripts that do some other irrelevant things.我正在尝试制作一个基于控制台的 Java 应用程序,该应用程序启动一些批处理脚本来执行其他一些不相关的事情。 Presently, I just want to find the proof of concept目前,我只想找到概念证明

I have tried to use the following code:我尝试使用以下代码:

Runtime.getRuntime().exec("cmd /c start pathtomybatch.bat"); 

This works fine until I turn it into a .jar file and attempt to execute it.在我将它转换为.jar文件并尝试执行它之前,它工作正常。 Then it opens the batch file in a new command prompt window, which I don't want it to do.然后它在新的命令提示符窗口中打开批处理文件,我不希望它这样做。 I want to open the batch file in the same window that my Java program is running in. I read about the start command on TechNet and SS64 and found out that apparently adding changing start to start /b would open the program in the same command prompt window.我想在运行我的 Java 程序的同一窗口中打开批处理文件。我在TechNetSS64上阅读了有关start命令的信息,发现显然将更改start添加到start /b会在同一命令提示符下打开程序窗户。 However, when I try to run this:但是,当我尝试运行它时:

Runtime.getRuntime().exec("cmd /c start /b pathtomybatch.bat"); 

NetBeans says BUILD SUCCESSFUL for both lines of code, but when I try the second line of code, no command prompt window opens and my batch file doesn't get started. NetBeans 对两行代码都显示BUILD SUCCESSFUL ,但是当我尝试第二行代码时,没有命令提示符窗口打开,我的批处理文件也没有启动。

I want to know how I can make Java open that batch file within the same command prompt window without stopping the Java application or waiting for it to finish.我想知道如何让 Java 在同一个命令提示符窗口中打开该批处理文件,而无需停止 Java 应用程序或等待它完成。

Also, as a tiny extra request, could someone tell me if I could do the same for an .exe file?另外,作为一个小小的额外请求,有人可以告诉我是否可以对.exe文件执行相同的操作吗?

I'm on Windows 7, but I want this app to work for people using Vista or newer.我使用的是 Windows 7,但我希望此应用程序适用于使用 Vista 或更高版本的用户。

The extra window is coming from the start command you initiate.额外的窗口来自您启动的启动命令。 See https://www.windows-commandline.com/cmd-start-command/请参阅https://www.windows-commandline.com/cmd-start-command/

A better pattern is to use更好的模式是使用

Process p = Runtime.getRuntime().exec("cmd /c pathtomybatch.bat"); 

Then make sure you loop until p.exitValue() no longer throws an exception (which means the process has exited), and while looping copy all available bytes from p.getOutputStream() and p.getErrorStream() to System.out and/or System.err.然后确保循环直到 p.exitValue() 不再抛出异常(这意味着进程已退出),并在循环时将所有可用字节从 p.getOutputStream() 和 p.getErrorStream() 复制到 System.out 和/或 System.err。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM