我正在尝试创建一个程序(个人练习)来访问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键进入访问高级模式,则响应将消失。 有没有办法解决?
尝试这种方法:
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();
}