Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
hi all,
Can we call(run) unix commands through a java program? Plzz let me know....Actually i want the commands like "ls" to run automatically when some event occurs & then i want to store its output in a file by redirecting it.
if anybody knows any link or the solution...plzz tell me..
Thanx in advance....waiting 4 ur reply....

use the java.lang.Runtime's exec() method.
this is documented at;
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.htmlAs for redirecting output to a file i am having problems running commands with output redirection under Redhat Linux 9. The > symbol is not being interpreted correctly. For example ls > fred.txt results in an error message >: No such file or directory. A work around is to use a shell script or don't use redirection and read the commands stdout via your Java. It depends on what you ultimately want to do with the commands output.
Below is a code example. Simply change the values of cmd and workDir to suit your situation.
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;/**
* @author wharfie
* 2004-02-27
* Run a system command
*/
public class RunSystemCommand {
public static void main(String args[]) {
String s = null;
// system command to run
String cmd = "ls > fred.txt";
// set the working directory for the OS command processor
File workDir = new File("/dir1/dir2");try {
Process p = Runtime.getRuntime().exec(cmd, null, workDir);
int i = p.waitFor();
if (i == 0){
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// read the output from the command
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
else {
BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
while ((s = stdErr.readLine()) != null) {
System.out.println(s);
}}
}
catch (Exception e) {
System.out.println(e);
}
}
}

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |