在 Java 中,允许程序向 CMD.exe 发送命令的小帮助
Posted
技术标签:
【中文标题】在 Java 中,允许程序向 CMD.exe 发送命令的小帮助【英文标题】:In Java, a small help to allow a program send commands to CMD.exe 【发布时间】:2020-09-29 01:25:40 【问题描述】:我正在尝试创建一个程序(个人练习)来访问 CMD 并键入您想要的任何命令,就好像您正在使用 cmd.exe 一样;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CMD_Live
public static void main(String[] args) throws IOException
// The purpose of this program is to use Java to perform CMD commands as if you are working on it live
Scanner ScanCMD = new Scanner(System.in);
while(true)
System.out.print("Insert your Command> ");
String CMDcommand = ScanCMD.nextLine();
Process processToCMD = Runtime.getRuntime().exec(CMDcommand);
BufferedReader readerToCMD = new BufferedReader(new InputStreamReader(processToCMD.getInputStream()));
String line;
while ((line = readerToCMD.readLine()) != null)
System.out.println(line);
System.out.println();
readerToCMD.close();
这段代码的问题是,它适用于简单的命令, 例如 ping google.com,或 nslookup google.com,
但如果我插入 nslookup 并按 Enter 进入高级模式,那么响应就会消失。 有办法解决吗?
【问题讨论】:
最后再次使用 System.in.readLine 吗? 【参考方案1】:这应该适合你:
ProcessBuilder processBuilder = new ProcessBuilder(CMDcommand); //note, that you can build your command here step by step.
Process process = processBuilder.start();
String response = null;
InputStream inputStream = process.getInputStream();
BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(inputStream));
//and then do whatever you want to do.. my example is this:
while(response=bufferedInputStream.readLine()!=null)
..some code..
catch (IOException e)
e.printStackTrace();
【讨论】:
以上是关于在 Java 中,允许程序向 CMD.exe 发送命令的小帮助的主要内容,如果未能解决你的问题,请参考以下文章
如何在 cmd.exe 中将 stderr 重定向到 null