Reputation: 1245
My problem is, after opening cmd from java code, i want user to be able to input like in c++ ms dos applications. When user writes sth such as "dir" or "cd..", i want to execute these codes by java. The problem is for every command java re-opens cmd again. Also i cannot execute commands. My cmd start code is below ;
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();
Upvotes: 2
Views: 1368
Reputation: 30152
Here's some cleaned up code from 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()); } }
Upvotes: 1