在Java中,这是一个很小的帮助,允许程序将命令发送到CMD.exe

问题描述 投票:1回答:1

我正在尝试创建一个程序(个人练习)来访问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.comnslookup google.com

但是如果我插入nslookup并按Enter键进入访问高级模式,则​​响应将消失。 有没有办法解决?

java cmd command-line operating-system command
1个回答
0
投票

尝试这种方法:

ProcessBuilder processBuilder = new ProcessBuilder("command..");
Process process = processBuilder.start();

InputStream inputStream = process.getInputStream();
BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(inputStream));

while(bufferedInputStream.readLine()!=null) {

}
} catch (IOException e) {
    e.printStackTrace();
}
© www.soinside.com 2019 - 2024. All rights reserved.