我的问题是,在从java代码打开cmd之后,我希望用户能够像在c ++ ms dos应用程序中那样输入。当用户写道时,例如" dir"或者" cd ..",我想用java执行这些代码。 问题是每个命令java再次重新打开cmd。我也无法执行命令。我的cmd开始代码如下;
final ArrayList<String> commands = new ArrayList<>();
commands.add("cmd.exe");
commands.add("/C");
commands.add("start");
ProcessBuilder pb = new ProcessBuilder(commands);
Process process = pb.start();
答案 0 :(得分:1)
以下是How to open the command prompt and insert commands using Java?
中的一些清理代码public static void main(String[] args) { try { String ss = null; Runtime obj = null; Process p = Runtime.getRuntime().exec("cmd.exe"); //write a command to the output stream BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); writer.write("dir"); writer.flush(); //Get the input and stderror BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Here is the standard output of the command:\n"); while ((ss = stdInput.readLine()) != null) { System.out.println(ss); } System.out.println("Here is the standard error of the command (if any):\n"); while ((ss = stdError.readLine()) != null) { System.out.println(ss); } } catch (IOException e) { System.out.println("FROM CATCH" + e.toString()); } }