简体   繁体   中英

command does not execute successfully when run through java code using runtime.getruntime command

I have a command which executes successfully when run directly in a command prompt but when same command is run through java code using runtime.getruntime.exec("command"); it does not give the desired output. why is it not running properly??

The command i am executing is to change the admin password and the command output i want to redirect into a file. The command is as follows:

Process p=Runtime.getRuntime().exec("net user administrator 1234 > yjs.txt 2>&1");

if i directly run "net user administrator 1234 > yjs.txt 2>&1" in my command prompt it executes correctly ie the text file yjs.txt is created and the ouptut is redirected into the file..

but when the same command i execute through a java code the file yjs.txt is not created at all.. It does not even give an error message when compiling. Any idea why??

Your command prompt does much more than just run an executable, which is what Runtime.exec() does. For example, the output-redirection ( > yjs.txt 2>&1 ) is a feature of your command prompt, but not a feature of Java.

If you want to redirect the output to a file, you have two options:

  • put the full command including the output-redirects into a batch-file (or shell-script, depending on your OS) and execute that batch-file from Java.
  • use the Process object returned by exec() and write the output- and error-stream you receive from that object to a file yourself.

Actually, you should do the second case anyway. If the command you start generates lots of output, it may start blocking if that output isn't consumed by your code. Have a look at http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html , it explains in large details the possible pitfalls of Runtime.exec() and also provides solutions for how to deal with it (for example by using the StreamGobbler in listing 4.5 of the article).

This is because the default sub-process created by the Runtime.getRuntime.exec() command does not have its own terminal or console. All its standard I/O (ie, stdin, stdout, stderr) will be redirected to the parent process and they can be accessed via getInputStream/getOutputStream/getErrorStream. You may try reading the output of the command "net user administrator 1234" through p.getOutputStream and write it explicitly to yjs.txt file using File I/O

Also, ProcessBuilder is the preferred way of executing commands unless you are stuck with ancient JVM. Refer http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html for examples and documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM