0

We are trying to write to STDIN of a command using the Runtime exec in Java. We use cmd /c to execute the command as Runtime exec will not recognise it without the cmd /c. This should write "q" and newline to a file called output.txt. We can find the file, but it does not have any contents.

String cmd = "cmd /c TYPE CON>output.txt";

try{
    process = Runtime.getRuntime().exec(cmd, null);
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    bufferedWriter.write("q");
    bufferedWriter.newLine();
    bufferedWriter.flush();
    bufferedWriter.close();
}catch(Exception e){}

We have also tried to use the output stream directly and write bytes without success.

It has to be a STDIN command, are we misunderstanding the process.getOutputStream()

We have verified that the same command works in the command prompt.

We are currently on Windows 10

We have tried provided solutions from stackoverflow and other sites, but to no avail.

  • Runtime.exec is ancient and obsolete. Use [ProcessBuilder](https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessBuilder.html) instead. Also, *never* write an empty `catch` block. At the very least, put `e.printStackTrace();` in it. – VGR Nov 28 '17 at 16:50
  • Take a look at [this answer](https://stackoverflow.com/a/35261487/2979435) – deFreitas Nov 29 '17 at 00:39
  • 1) See also [When Runtime.exec() won't](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html) for many good tips on creating and handling a process correctly. Then ignore it refers to `exec` and use a `ProcessBuilder` to create the process. Also break a `String arg` into `String[] args` to account for things like paths containing space characters. 2) Don't ignore exceptions! They inform us exactly what went wrong. Unless logging is implemented, at least call `Throwable.printStackTrace()` 3) *"We have tried provided solutions from stackoverflow and other sites"* .. – Andrew Thompson Nov 29 '17 at 01:35
  • What solutions? Be ***specific!*** Both SO and 'other sites' covers a vast range of possibilities. – Andrew Thompson Nov 29 '17 at 01:36
  • Alright, we believe that this is because of the cmd /c command. The STDIN seems to go to the cmd /c command and does not get forwarded to the TYPE CON command. We have not found a solution to this – user2873958 Dec 05 '17 at 12:52

0 Answers0