Running Echo from Java

I am trying to use the Runtime.exec () method to start a command line process.

I wrote this sample code that works without problems, but does not create the file in c: \ tmp.txt.

String cmdLine = "echo foo > c:\\tmp.txt";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmdLine);

BufferedReader input = new BufferedReader(
                           new InputStreamReader(pr.getInputStream()));
String line;

StringBuilder output = new StringBuilder();
while ((line = input.readLine()) != null) {
    output.append(line);
}

int exitVal = pr.waitFor();

logger.info(String.format("Ran command '%s', got exit code %d, output:\n%s", cmdLine, exitVal, output));

Output signal

INFO 21-04 20: 02: 03,024 - the Ran command 'echo foo> c: \ tmp.txt', received exit code 0, output: foo> c: \ tmp.txt

+3
source share
3 answers

echo is not a standalone command under Windows, but is built into cmd.exe.

I believe that you need to call a command like "cmd.exe / C echo ...".

+8
source

>The shell is intrepreted when echoexecuted in the cmmand line, and it is the shell that creates the file.

Java, , :

"foo > c:\tmp.txt"

( , )

+4

" > c:\tmp.txt" Runtime.exec , . Javadocs: " io (.. Stdin, stdout, stderr) (getOutputStream(), getInputStream(), getErrorStream())."

, , - Java, getInputStream, .

+1

Source: https://habr.com/ru/post/1742135/


All Articles