Amit
asked on
Running a unix shell script through a java code
Hi,
I have a little java program that loads a file into a database. Now I need to insert a shell script in this java program or rather
I need to run a little shell command say ls -l through a java program. Any ideas or sample code
thanks
-amit
I have a little java program that loads a file into a database. Now I need to insert a shell script in this java program or rather
I need to run a little shell command say ls -l through a java program. Any ideas or sample code
thanks
-amit
If it is an external command - use http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec(java.lang.String[]) and start the sh or bash before invoking the actual script...
And an example how to use it: http://www.exampledepot.com/egs/java.lang/Exec.html
And an example how to use it: http://www.exampledepot.com/egs/java.lang/Exec.html
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
basav_com,
When someone had already proposed a solution and you want to mention it also, you should be giving credit to the first expert. We all try to help - let's work as a team and not as people that do not care for each other. Don't you think this will work better?
:) V
When someone had already proposed a solution and you want to mention it also, you should be giving credit to the first expert. We all try to help - let's work as a team and not as people that do not care for each other. Don't you think this will work better?
:) V
ASKER
Hi experts,
Since I am a newbie. Could you please send me a code or something
I need to do the following using java in Unix
1. cd /alpha/beta
2. ls -t xyz* | head -1
3. And then print the output of step 2
I tried the sample codes but couldn't go far
thanks
-anshu
Since I am a newbie. Could you please send me a code or something
I need to do the following using java in Unix
1. cd /alpha/beta
2. ls -t xyz* | head -1
3. And then print the output of step 2
I tried the sample codes but couldn't go far
thanks
-anshu
Hi amit,
As Venabili has mentioned about the Runtime class, Pls credit all the points to her only.
You can put above 3 steps in a single step as:
ls /alpha/beta -t xyz* | head -1 --- Once you execute this one thru Process p=Runtime.getRuntime().exe c("ls /alpha/beta -t xyz* | head -1");
Read the process inputstream p.getStream() and then print it.
OR
Create a temporary file(shell script) with the above commands and then execute that file.
Hi Venabili,
Ok sure. I will follow your suggestion. :)
As Venabili has mentioned about the Runtime class, Pls credit all the points to her only.
You can put above 3 steps in a single step as:
ls /alpha/beta -t xyz* | head -1 --- Once you execute this one thru Process p=Runtime.getRuntime().exe
Read the process inputstream p.getStream() and then print it.
OR
Create a temporary file(shell script) with the above commands and then execute that file.
Hi Venabili,
Ok sure. I will follow your suggestion. :)
anshuma,
Post the code that you tried and what is the result that you see and we will help you fix it.
basav_com,
It's not for the points. Split would be just fine. (let's just first help the asker)
Post the code that you tried and what is the result that you see and we will help you fix it.
basav_com,
It's not for the points. Split would be just fine. (let's just first help the asker)
ASKER
Here's the code
import java.io.*;
public class ShellScript {
public static void main(String args[]) {
String s = null;
try {
// run the Unix "ps -ef" command
Process p = Runtime.getRuntime().exec( "cd
/bia/opt/MicroStrategy");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInp utStream() ));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErr orStream() ));
// read the output from the command
System.out.println("Here is the standard output of the
command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command
(if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("Error - Details are below ");
e.printStackTrace();
System.exit(-1);
}
}
}
-------------------------- ---------- -------
Here's the error message
Error - Details are below
java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.s tart(Unkno wn Source)
at java.lang.Runtime.exec(Unk nown Source)
at java.lang.Runtime.exec(Unk nown Source)
at java.lang.Runtime.exec(Unk nown Source)
at ShellScript.main(ShellScri pt.java:17 )
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.<ini t>(Unknown Source)
at java.lang.ProcessImpl.star t(Unknown Source)
... 5 more
import java.io.*;
public class ShellScript {
public static void main(String args[]) {
String s = null;
try {
// run the Unix "ps -ef" command
Process p = Runtime.getRuntime().exec(
/bia/opt/MicroStrategy");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInp
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErr
// read the output from the command
System.out.println("Here is the standard output of the
command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command
(if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("Error - Details are below ");
e.printStackTrace();
System.exit(-1);
}
}
}
--------------------------
Here's the error message
Error - Details are below
java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.s
at java.lang.Runtime.exec(Unk
at java.lang.Runtime.exec(Unk
at java.lang.Runtime.exec(Unk
at ShellScript.main(ShellScri
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.<ini
at java.lang.ProcessImpl.star
... 5 more
This is because cd is internal command. The ls will work as described above but for cd you need somewhat more special treatment.
You will need to do it through the Process output stream. Something like this (if /bin is the initial working directory and if you want to use bash - change the paths if needed) This will behave as if you are typing on the console
Let me know if you need more assistance with this
PS: Why you need to do the cd at all - can't you just invoke the commands with giving the full path to the directory?
You will need to do it through the Process output stream. Something like this (if /bin is the initial working directory and if you want to use bash - change the paths if needed) This will behave as if you are typing on the console
Let me know if you need more assistance with this
PS: Why you need to do the cd at all - can't you just invoke the commands with giving the full path to the directory?
File workDirectory = new File("/bin");
Process process = null;
try {
process = runtime.getruntime().exec("/bin/bash", null, workDirectory );
}
catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())), true);
out.println("cd /bia/opt/MicroStrategy");
out.println("pwd"); // this will print where you are.
//other commands here
try {
process.waitFor();
in.close();
out.close();
process.destroy();
}
catch (Exception e) {
e.printStackTrace();
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi,
I ran the following code but it didn't do anything and it looked like nothing was happening. I waited for 3-4 minutes before I killed it :-(
thanks
-anshu
import java.io.*;
public class ShellScript {
public static void main(String args[])
{
File workDirectory = new File("/bin");
Process process = null;
try {
process = Runtime.getRuntime().exec( "/bin/bash ", null, workDirectory );
}
catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(process. getInputSt ream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process .getOutput Stream())) , true);
out.println("cd /bia/opt/MicroStrategy");
out.println("pwd"); // this will print where you are.
//other commands here
try {
process.waitFor();
in.close();
out.close();
process.destroy();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
I ran the following code but it didn't do anything and it looked like nothing was happening. I waited for 3-4 minutes before I killed it :-(
thanks
-anshu
import java.io.*;
public class ShellScript {
public static void main(String args[])
{
File workDirectory = new File("/bin");
Process process = null;
try {
process = Runtime.getRuntime().exec(
}
catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(process.
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process
out.println("cd /bia/opt/MicroStrategy");
out.println("pwd"); // this will print where you are.
//other commands here
try {
process.waitFor();
in.close();
out.close();
process.destroy();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
See my last comment please. :) You need this comment at the beginning of the try-catch for the closing
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
ASKER
Thanks and sorry for not watching your last comment. it seems better but still its not getting stopped moreover this is the output that I get
so its not printing
out.println("cd /bia/opt/MicroStrategy");
out.println("pwd"); // this will print where you are.
sorry for asking so many questions I am not good in java but I really need to get few things done. If you are exhausted then I can award points and close this question
__________________________ __________ __________ ________
-bash-3.00$ /usr/bin/java ShellScript
/bia/opt/MicroStrategy
[4]+ Stopped /usr/bin/java ShellScript
so its not printing
out.println("cd /bia/opt/MicroStrategy");
out.println("pwd"); // this will print where you are.
sorry for asking so many questions I am not good in java but I really need to get few things done. If you are exhausted then I can award points and close this question
__________________________
-bash-3.00$ /usr/bin/java ShellScript
/bia/opt/MicroStrategy
[4]+ Stopped /usr/bin/java ShellScript
Process p = Runtime.getRuntime().exec(
See http://www.devdaily.com/java/edu/pj/pj010016/pj010016.shtml for a way to handle the output and some explanations.