Problem in executing a unix command through java
hi
i'm trying to execute unix command through java
simple shell command like "ls -l >test " but i'm not able to see the result.
there are no error messages.
Code is:
import java.lang.Runtime.*;
class ExecDemo
public static void main(String[] args)
Runtime r=Runtime.getRuntime();
Process p=null;
try
p=r.exec("ls -l > test");
catch (Exception e)
System.out.println("Error executing nedit.");
}can anyone help please.
get the the inputStream of the runtime object after executing the command.
now use the readLine() function until it becomes null.
egs: with reference to ur code.
InputStream is=p.getInputStream()
while(is!=null)
String s=is.readLine();
if the command don't execute try giving the full path also like /sbin/ls -l
Similar Messages
-
Executing Unix command through Java
Hi,
Hi, I am trying to run some unix command through:
Runtime.getRuntime().exec("some unix command line");
I am running the code on Linux platform. However, I always got some errors. Here are the stack trace of them:
java.io.IOException: Cannot allocate memory
java.io.IOException: java.io.IOException: Cannot allocate memory
at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
at java.lang.ProcessImpl.start(ProcessImpl.java:65)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
at java.lang.Runtime.exec(Runtime.java:591)
at java.lang.Runtime.exec(Runtime.java:429)
at java.lang.Runtime.exec(Runtime.java:326)Anybody has any idea why is this happening? Thanks.
AuliaHi, thanks for your reply so far. I tried the following code:
public boolean executeCommand() {
boolean success = true;
for (int i = 0; i < 5; i++) {
Process p = null;
try {
p = Runtime
.getRuntime()
.exec("ls");
InputStreamReader inR = new InputStreamReader(p
.getErrorStream());
BufferedReader buf = new BufferedReader(inR);
String line;
while ((line = buf.readLine()) != null) {
System.out.println(line);
p.destroy();
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
success = false;
} finally {
p = null;
return success;
}However, it still throws the same exception. Yes, I put it in a tight loop, but not recursively. -
GETTING THE OUPUT OF UNIX COMMAND THROUGH JAVA
Hi Guyz...
Please help me in the below code...
My intention is to print the output of Unix command through a java program.
The Java program resides in the Unix Server only.
I have written the below java code , but its not returning any values....
String s1= "ls -lt $APPL_TOP/patch/115/odf/jtfgh.odf";
Runtime r = Runtime.getRuntime();
Process p= r.exec(s1);
StringBuffer ret=new StringBuffer();
InputStream in = p.getInputStream();
int c;
while ((c = in.read()) != -1)
{ ret.append((char)c);
} in.close();
out.println("OTUPUT : "+ ret.toString());
Can you please help me in this by debugging the existing code or giving me the exact code??
IT IS URGENT FOR MY PROJECT!!!!!!!!!!!!!!!!!!!!!!!!!!!
PLEASE HELP ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Since you are expecting the shell to expand the environment variable you need to use
String[] s1= {"sh","-c","ls -lt $APPL_TOP/patch/115/odf/jtfgh.odf"};
Also, you should read, digest and implement the recommendations of
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html .
P.S Your urgency is not my problem and SHOUTING IS CONSIDERED VERY RUDE! -
Executing the top command through Java in linux
I am trying to execute the top command in Java as
Runtime.getRuntime().exec("top -n 1 >a.log");
But the command is not working in linux only through java.When i run the same command through the prompt it is working fine.Also all other commands are working fine.Is there any issue with top in linux?flounder wrote:
Try reading [this article|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. If it does not answer your problem then try seaching for other similar articles.
The cited article does provide an answer to the problem since it explains how the shell meta character '>' must be interpretted by a shell. The code as presented does not invoke a shell. -
How to execute a Unix Command in java
Hi, Iam trying to execute a unix command on Sun Solaris by passing that command to a java program. How can I achieve this?
Thanks in advance.Have a look at the javadoc around the Runtime.exec() method. If the command is a shell command then you might have to execute a shell as well as the command.
For example, if you wanted to run a unix command 'ls -l > output.txt' the you might have to pass the following string into the exec() method,
"/bin/sh ls -l > output.txt' -
Running Unix command through Java
Hi
I am trying to run the unix command "rf filename" through Java and it doesnt seem to work.
Can anyone help in this case please
String cm = "rm ";
String delFile = args[0]; // this path is /data/temp/filename.doc
Process p = Runtime.getRuntime.exec(cmd +delFile);Also since i dont have access to delete the file through my login i always login as root for a few commands.
Is there a way i can specify user name & password & then run the command?
Please let me know
ThanxPlease discard the above msg i got a solution by just adding file.delete
thanx -
Hi all,
I was trying to execute the following code:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
* Created on Mar 13, 2007
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
* @author 195092
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
public class ClassReportDeleteDaemon {
ClassReportDeleteDaemon()
public static void main(String[] args) throws Exception
Connection conn = null;
Statement stmt = null;
ResultSet rs;
String strQuery = null;
String strdaysback = null;
String delstring = null;
int daysback;
try
System.out.println("REPORT DELETION ::: FINDING DRIVER");
Class.forName("oracle.jdbc.driver.OracleDriver");
catch(Exception e)
System.out.println("REPORT DELETION ::: DRIVER EXCEPTION--" + e.getMessage());
System.out.println("REPORT DELETION ::: DRIVER NOT FOUND");
try
String strUrl = "jdbc:Oracle:thin:" + args[0] + "/" + args[1] + "@" + args[2];
System.out.println("REPORT DELETION ::: TRYING FOR JDBC CONNECTION");
conn = DriverManager.getConnection(strUrl);
System.out.println("REPORT DELETION ::: SUCCESSFUL CONNECTION");
while(true)
System.out.println("WHILE LOOP");
stmt = conn.createStatement();
strQuery = "SELECT REP_DAYS_OLD FROM T_REPORT_DEL";
rs = stmt.executeQuery(strQuery);
while(rs.next())
strdaysback = rs.getString("REP_DAYS_OLD");
//daysback = Integer.parseInt(strdaysback);
System.out.print("NO of Days===>" + strdaysback);
delstring = "find /tmp/reports1 -name " + "\"" + "*" + "\"" + " -mtime +" + strdaysback + " -print|xargs rm -r";
System.out.println("DELETE STRING===>" + delstring);
Process proc = Runtime.getRuntime().exec(delstring);
//Get error stream to display error messages encountered during execution of command
InputStream errStream=proc.getErrorStream();
//Get error stream to display output messages encountered during execution of command
InputStream inStream = proc.getInputStream();
InputStreamReader strReader = new InputStreamReader(errStream);
BufferedReader br = new BufferedReader(strReader);
String strLine = null;
while((strLine=br.readLine())!=null)
System.out.println(strLine);
} //end of while loop
} //end of try
catch (Exception e)
System.out.println("REPORT DELETION ::: EXCEPTION---" + e.getMessage());
conn.close();
} //end of main
} //end of ClassReportDeleteDaemon
But it is giving the error "BAD OPTION -print|xargs". The command run well in shell.
Please help.
Thanking u.......Since the pipe '|' is interpreted by the shell then you need the shell to invoke your command
String[] command = {"sh","-c","find /tmp/reports1 -name " + "\"" + "*" + "\"" + " -mtime +" + strdaysback + " -print|xargs rm -r"};
final Process process = Runtime.getRuntime().exec(command);
You should also read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html at least twice and implement the recommendation regarding stdout and stderr.
P.S. Why are you not using Java to find and delete these files?
Message was edited by:
sabre150 -
How to execute MS DOS command through Java program???
Dear Sir,
I want to run a MS-DOS command through my Java program. I have tried "Dir" command but no other command which takes command line args doesn't work at all. Please help.
import java.io.*;
class CommandPrompt
public static void main(String[] args)
try
File file = new File("C:/Temp/Java");
String[] cmd = {"command.com","/c","md folder"};
String[] envp = {""};
Process m;
String s = "";
m = Runtime.getRuntime().exec(cmd,null,file);
BufferedReader buf = new BufferedReader(new InputStreamReader(m.getInputStream()));
while ((s = buf.readLine())!=null)
System.out.println(s);
catch (Exception ex)
System.out.println("Exception is "+ex);
ex.printStackTrace();1. This forum is for Swing-related issues only. This question should be posted to the "Java Programming" forum.
2. Please enclose your sample code in code blocks; it's much easier to read that way. See here for how it's done: http://forum.java.sun.com/faq.jsp#messageformat
3. Please provide more information, like what error messages you got and what OS you're running. For instance, if you're running WinXP, Win2k or NT4, your command processor should be "cmd.exe", not "command.com". When I made that change, your program worked for me. -
Problems to execute "cd" DOS command from Java program
Anyone try to exec command "cd.." or "cd directory", it doesn't have any action. No exceptions, just don't do anything.
Runtime.getRuntime().exec("cd\\");
Runtime.getRuntime().exec("cd hello");
However, when I try the following, it is working fine. Any ideas???
Runtime.getRuntime().exec("explorer");
Runtime.getRuntime().exec("javac Test1.java");That's because cd is built into the command
interpreter in Windows. Runtime.getRuntime().exec()
can only be used to launch external programs. This
article should get you going:And that's not the only reason why you can't do this.
When you do
Runtime.getRuntime().exec("cd c:\\");
(or, heck, "cmd /c cd c:\\"): the new command that you spawn will cd to the destination specified, and then exit. The parent process (your java program, that is launching this command) won't go anywhere - the "cd" doesn't affect it.
The only way to change your OS directory in Java is to invoke native code. And even then, the effects are undefined (in terms of how your CLASSPATH will be affected, etc.). -
How to execute unix command in java or jsp
have a peace day,
please send some sample code for
"execute the unix command in java or jsp"
thank you
regards
rexi execute this coding
its compiling. while running i get the error " java.io.IOException: CreateProcess: \ls-l error=2 "
import java.io.*;
import java.util.*;
public class Test
public static void main(String[] args) throws Exception
try
String[] cmd = {"/ls-l"};
Runtime.getRuntime().exec(cmd);
catch (Exception e)
System.out.println(e);
}what can i do for that
thank u -
Execute unix command using java
Hello
Can we execute a unix command using java? If it is how we can execute. Is this affect the performance of the program.
ThanksI tried what you said. But its not working and returning error message,
java.io.IOException: CreateProcess: ls -a error=2
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
If i try this statement,
Runtime.getRuntime().exec("c\windows\notepad");
It is working fine.
Any idea about this.
Plz ........... -
Execute unix commands from Java
Hi,
I have a client application running on windows. This client should connect to a unix server and check for the existence of a file and display the result as "File found/File not found". In order to connect from windows to the unix server, I used the sockets and the connection is successfully established. The second part is to check for the presence of the file in unix server. I searched in google.com and the option I found to execute a unix command from java is the "Runtime.exec()". Runtime.exec is considered as the less effective (not a favorable) one.
Is there any other option available (other than the Runtime) to execute the unix command from java? Can you please let me know.
Thanks a lot
AishuSo, please let me know how I can execute the above unix commands without Runtime.exec()You have a client and a server.
You want something to run on the server, not the client.
That means that something must in fact being running on the server before the client does anything at all.
For example telnet. Or a J2EE server application.
So is something like that running?
If not then there absolutely no way to do what you want, even with Runtime.exec().
If yes then what you do depends on what is running. So Runtime.exec() would be pointless if a J2EE server was running. -
Permission denied when I execute a unix command from within my java applet.
Hi Gang,
Forgive me if this is not the appropriate forum for this problem. I'm posting this problem on this forum since I got no answers on the other forum I posted on.
I've written a simple java applet that runs a unix command and then displays some information. The applet compiles fine, and runs perfectly from the command line on my unix system.
However, when I point a browser at the applet from my desktop PC I get the following error as taken from the java console:
Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
This is of course the first line in a long line of error messages. It appears that I am not able to execute a command on the unix system through my applet. I know the problem is with trying to execute a unix command since commenting it causes no error in the web browser. This is the command I'm using in java to execute the unix command:
p = Runtime.getRuntime().exec("ps");
Here's the html file on the unix system:
<html>
<head></head>
<body>
<appletcode=G.class height="250" width="400">
Your browser does not support the applet tag.
</applet>
</body>
</html>
I won't list the java code since it is compiling and working on the command line. But, if you want to see it I'll provide it.
I've done quite a bit of research on this and it seems that a great number of people have similar problems reading or executing files through java. I have yet to find a solution to this problem.
Here are some details about my setup:
Server:
HP9000 running HP/UX 11.23
Apache Web Server 2.0.35
Java 1.5
Desktop PC:
Win2K Pro
Internet Explorer 6
Java 1.6
If you have a solution I would be very grateful! This problem is keeping me from writing my application!
thanks!
kevMulti-posted.
Already answered here http://forum.java.sun.com/thread.jspa?threadID=5225314&messageID=9916327#9916327 -
Permission denied when I execute a unix command from inside my Java applet.
Hi Gang,
Forgive me if I'm posting this to the wrong forum! I didn't get any answers on the previous forum that I posted this to.
I've written a simple java applet that runs a unix command and then displays some information. The applet compiles fine, and runs perfectly from the command line on my unix system.
However, when I point a browser at the applet from my desktop PC I get the following error as taken from the java console:
Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
This is of course the first line in a long line of error messages. It appears that I am not able to execute a command on the unix system through my applet. I know the problem is with trying to execute a unix command since commenting it causes no error in the web browser. This is the command I'm using in java to execute the unix command:
p = Runtime.getRuntime().exec("ps");
Here's the html file on the unix system:
<html>
<head></head>
<body>
<appletcode=G.class height="250" width="400">
Your browser does not support the applet tag.
</applet>
</body>
</html>
I won't list the java code since it is compiling and working on the command line. But, if you want to see it I'll provide it.
I've done quite a bit of research on this and it seems that a great number of people have similar problems reading or executing files through java. I have yet to find a solution to this problem.
Here are some details about my setup:
Server:
HP9000 running HP/UX 11.23
Apache Web Server 2.0.35
Java 1.5
Desktop PC:
Win2K Pro
Internet Explorer 6
Java 1.6
If you have a solution I would be very grateful! This problem is keeping me from writing my application!
thanks!
kevMulti-posted.
Already answered here http://forum.java.sun.com/thread.jspa?threadID=5225314&messageID=9916327#9916327 -
Execute dos commands through java
Hi,
Im trying to execute dos commands through java like
try {
java.lang.Runtime.getRuntime().exec("cmd /c cls");
}catch(IOException e){
System.out.println(e.getMessage());
}Not sure if its possible? however
open notepad would work
try {
java.lang.Runtime.getRuntime().exec("notepad");
}catch(IOException e){
System.out.println(e.getMessage());
}Im trying to execute a cls commands to clear screen but without luck.The question is, which shell do you want to clear?
I don't really know, but it could be that Runtime.exec executes its command in a new shell window...
Maybe you are looking for
-
Blank printout in report 6i from Application server oracle 9i
Hello, 3 days before our application server (oracle 9i for windows NT 1.0.2.0.0) hard disk crashed. We have installed AS. Now when user runs report from client pc and selects destination type as "cache" and submit query he can see the output. When he
-
How do I transfer photos from iPad to iPhone 5?
Transfer photos
-
Xbox/express problem gets stuck at 11mbs
First post I looked all over and couldn't find my answer if its here sorry for this post. I have an Airport Extreme connected to a modem, the modem is in bridge mode. I have the xbox plugged into the lan port on the airport extreme. When I am wired i
-
I can't find the tool bar anywhere despite reading all the explanations it's nowhere to be found
On the top left hand side is a small orange bar which says Firefox and has an arrow to find topics. I tried to find tools there but was completely unsuccessful. I recently had Windows 7 installed on my computer to replace XP and now I don't have a to
-
Hi All, I am currently developing application using Oracle XE and APEX. I want to create installation CD that includes my product and Oracle XE database software. I want to know, will there be any licensing issues from Oracle Corp that I need to fulf