Thursday, September 18, 2008

How to Run Unix shell script in java

I came across the scenario wherein i have to call/ Run the unix shell script. I think this would help you guys.

I have written a script called custom_script.sh.

custom_script.sh code:

cp /home/Example.java /home/Example_copy.java

In this script just i am copying a file to another.

The java code to call that script.

import java.io.BufferedWriter;
import java.io.*;
public class CallScript
{
public static void main(String s[]) throws Exception{
Runtime rt = Runtime.getRuntime();
try {
String str = "/absolute_path/test.sh";
Process child = rt.exec("/bin/bash");
BufferedWriter outCommand = new BufferedWriter(new Output
StreamWriter(child.getOutputStream()));
outCommand.write(str +"\n");
outCommand.flush();

} catch (Exception e) {
e.printStackTrace();
}
}
}

0 comments:

Post a Comment