Running command line commands through java
How do I run other programs through Java and capture their output. E.g. If I want to capture output of 'ls *.txt' what do I do ? If you can paste some sample code or point me to some tutorial that would be cool.
Thanks,
I tried that
Process proc = Runtime.getRunTime().exec("curl " + query);
but now what. From the documentation I could see that
public abstract OutputStream getOutputStream()
might be helpful. But then which OutputStream class to use ? I am looking for a coding example. If you could paste it, that would be great.
Similar Messages
-
Run Command through Java Program.
I am giving ping command in exec method of Runtime().
But ping syntax is different for linux and windows. So when I run command on windows it wasn't worked. I am giving command --> ping -c5 ipaddress . This works fine for linux but in windows, there is no -c option. So is there any solution to overcome this situation?
please reply ASAP.
Thanks,
RajI am writing code that runs ping command on all OS.
Ping syntax different for different OS (like
windows,linux,solaris etc).
I don't want to check for each OS and run command
specific to that OS.
I want to write a generic program so ping command
execute regardless of which OS. This is self-contradictory. You can't use one command line string on different platforms if they don't support this one command string.
The ping command is different (concretely, this -c option you mention is indeed not supported on Windows - what does it do anyway?) on different OS.
So, you basically have two options:
- You use only a subset of the ping options, one that does run on all your platforms (I actually expect ping to be pretty portable anyway but...).
- Or you do use platform specific options like -c, in which case there's no way around checking the running OS and generating a specific command line.
Can I use system calls in my program to execute the
ping command, If yes, how?Rephrase please. -
Running cmd commands through java
Hi,
I am trying to run few dos commands through java using Runtime.exec("command") but I am getting following error
commmand is cd D:\CodeMerge\A\
java.io.IOException: CreateProcess: cd.. error=2
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Unknown Source)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at createDirectory.main(createDirectory.java:24)
Basically what I am looking for is this:
1) My program is in D:\Amit\RM
2) I want to get out to D:\ go to CodeMerge\A\.
3) Create folder with curretn date as name of the folder
Hence I am doing
rTime.exec("cd../..");
rTime.exec("cd D:\CodeMerge\A\");
rTime.exec("mkdir "+date);
Can anybody tell me why I am getting this error
JountyU can run either DOS Commands or UNIX Commands thru the following Java Program
Written By BalaNagaraju Malisetti
contact: [email protected]
import java.io.*;
public class RunBdiff
public static String rununixcmd(String v_prev_path,String v_curr_path,String v_delta_path,String v_beg,String v_len)
String s = null;
FileOutputStream fos;
DataOutputStream dos;
try
int v_int_beg = Integer.parseInt(v_beg);
int v_int_len=Integer.parseInt(v_len);
int v_int_end=(v_int_beg+v_int_len)-1;
String v_pos1=String.valueOf((v_int_beg+2));
String v_pos2=String.valueOf((v_int_end+2));
String cmd1 = "bdiff ";
String cmd2=v_prev_path;
String cmd3=" ";
String cmd4=v_curr_path;
String cmd5="| grep '^>'";
String cmd6="| cut -c";
String cmd7=v_pos1+"-"+v_pos2;
String cmd8="| sort ";
String cmd9="| uniq ";
String cmd=cmd1+cmd2+cmd3+cmd4+cmd5+cmd6+cmd7+cmd8+cmd9;
String[] commands = {"/bin/csh","-c",cmd}; //in Unix
//String[] commands = {"cmd.exe","-c",cmd}; //in Windows
Process p = Runtime.getRuntime().exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
File file = new File(v_delta_path);
fos = new FileOutputStream(file);
dos=new DataOutputStream(fos);
//Writing the output of bdiff command to Delta File
while ((s = stdInput.readLine()) != null)
dos.writeChars(s);
//Return Error Message to Calling Procedure
while ((s = stdError.readLine()) != null)
return s;
return s;
catch (IOException e)
return String.valueOf(e);
public static void main(String args[])
String msg=rununixcmd("/home/g_anil/MS_ADDRESS1.dat","/home/g_anil/MS_ADDRESS2.dat","/home/g_anil/MS_ADDRESS_DELTA.dat","1","9");
************************************************************************************************************************************** -
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 -
Error running command: /usr/java/bin/java: error execing process: Not enough space
In a whole root zfs zone the webconsole service fails to start. This is what I get:
svc:/system/webconsole:console (java web console)
State: maintenance since Fri Aug 27 14:32:41 2010
Reason: Start method exited with $SMF_EXIT_ERR_FATAL.
See: http://sun.com/msg/SMF-8000-KS
See: man -M /usr/share/man -s 1M smcwebserver
See: /var/svc/log/system-webconsole:console.log
Impact: This service is not running.
# more /var/svc/log/system-webconsole:console.log
^C# more /var/svc/log/system-webconsole:console.log
[ Aug 6 09:30:40 Disabled. ]
[ Aug 6 09:30:40 Rereading configuration. ] [ Aug 6 09:30:52 Enabled. ] [ Aug 6 11:32:50 Enabled. ] [ Aug 6 11:33:02 Executing start method ("/lib/svc/method/svc-webconsole start"
Starting Sun Java(TM) Web Console Version 3.1 ...
The console is running.
[ Aug 6 11:33:25 Method "start" exited with status 0 ] [ Aug 27 14:32:15 Enabled. ] [ Aug 27 14:32:28 Executing start method ("/lib/svc/method/svc-webconsole start"
Error running command: /usr/java/bin/java: error execing process: Not enough spa ce [ Aug 27 14:32:41 Method "start" exited with status 95 ] # df -k
Filesystem kbytes used avail capacity Mounted on
/ 0 4341506 3761710 54% /
/dev 8103216 4341506 3761710 54% /dev
proc 0 0 0 0% /proc
ctfs 0 0 0 0% /system/contract
mnttab 0 0 0 0% /etc/mnttab
objfs 0 0 0 0% /system/object
swap 2498344 360 2497984 1% /etc/svc/volatile
/platform/SUNW,T5240/lib/libc_psr/libc_psr_hwcap2.so.1
8103216 4341506 3761710 54% /platform/sun4v/lib/libc_psr.so.1
/platform/SUNW,T5240/lib/sparcv9/libc_psr/libc_psr_hwcap2.so.1
8103216 4341506 3761710 54% /platform/sun4v/lib/sparcv9/libc_psr.so.1
fd 0 0 0 0% /dev/fd
swap 2497984 0 2497984 0% /tmp
swap 2498024 40 2497984 1% /var/run
Grp-MFNY/billables/RV
20514816 22 3761710 1% /RV
Grp-MFNY/billables/TT_DB
20514816 28 3761710 1% /TT_DB
Grp-MFNY/billables/tabYou need to find the java exceptions - most likely in the logs in the /var/log/webconsole/console directory.
A wild guess is you don't have enough swap space to perform a fork.
-- Ken -
What is the best way to call SSH commands through Java technologies
What is the best way to call SSH commands through Java technologies
I don't think you can specify the password at the prompt using ssh. Plink has the -pw command option for passwords. What I did was except ssh to ask me and write the password programmatically through the outputStream I obtained from my Process object. I looked for "password: ", and then wrote the password with a trailing newline.
Both plink and ssh will also ask if you trust the host if it is the first time you are connecting to it. So before just writing the password, check if the program wants verification from you: normally supplying "y" or "n". This should only have to happen the first time the client connects. It looks like thisPLINK:
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's key fingerprint is:
1024 f8:43:61:4c:a2:5b:77:be:5b:a7:bb:1f:f7:79:b3:b7
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)
SSH:
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
RSA key fingerprint is e1:02:13:c8:52:c2:23:41:9b:5b:58:2c:18:e6:59:af.
Are you sure you want to continue connecting (yes/no)?What I did was read character by character from the inputStream until I found things of interest ... like "password: ". You only need to search for this in your method which will launch the ssh or plink Process. Once you have verifyed yourself, you can just pass commands to the Process, which is an ssh connection.
My suggestion is to read() each byte from the Process's inputStream and write it to stdout. Look and see what you need to be looking for so you can interactive with the program correctly. You can't use readLine here becuase when the ssh asks for the password it does not print a newline. I do know for sure, that ssh will simply print, "passowrd: ". Plink will print this as well if the -pw option is not supplied. -
Accessing OS level commands through Java?
Hello everyone,
Is it possible to access OS-level (Unix BSD for instance) commands through Java classes or methods?
"OS-level commands" refers strictly to Unix commands such as I/O CTL (control), Poll and Select through a file descriptor.
"Access" refers to legitimate, built-in OR illegitimate (forced by "fooling" the system) access.However, the calls that you refer to, have been implemented in java; that goes for read/write/select (java.io and java.nio). But they pass through the java api implementation, and then throught the native implementation inside the JVM. If you want to use the raw power of poll() through java, you'd have to implement it yourself in JNI. But even if you successfully implement that, you must always remember that you'd have to make corresponding java classes that serve as arguments to your call, which, inside C, you must unpack again - so there goes your speed-advantage out the window.
-
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... -
Running Unix Shell scripts through Java
How to run Unix shell scripts through Java program ?
Use:
Process p = Runtime.getRuntime().exec("sh script.sh");Then you can use:
p.getOutputStream and read the output of your program. -
Running a shell script through java
Hi all,
I have a simple question here.
How can I run a shell script through java and put the text output into a string.
I'd be very grateful if you could show me sample code...
Have a great day,
PeshoRuntime.exec()
There are plenty of examples. Read the following before continuing, however, as it will save alot of headaches:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html -
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 -
How to run a command prompt " command " through java code
hi all,
There is a command
"java -jar selenium-server.jar -interactive"
which i am running through command prompt after going to D:\MyFolder\Examples .
i want to execute this command using java code .please helpThis has already been answered in your other two threads on this topic - http://forum.java.sun.com/thread.jspa?threadID=5221221&messageID=9898287#9898287 and http://forum.java.sun.com/thread.jspa?threadID=5221223&messageID=9898290#9898290.
For some reason you don't want to read the reference that tells you exactly how to do what you want and how to avoid the pitfalls - http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html . -
Running a exe (java command) through Java Code
Hi I have a program that runs on command line using java command.This program processes a text file that it takes as an argument.I have many files to process so I cannot give command for each individual file.
Is it possible that I use Java command to run this program for many files in a loop?
If yes HOW?It has many parameters but one parameter for input file. But I think this is not a problem, I can change it as you said.Now I have tried this code:
Note:In this code I can change B.txt each time in a loop for new input file. (This is just for check)
import java.io.*;
public class Test3
public static void main(String[] args)
Runtime run = Runtime.getRuntime();
try
Process pp=run.exec("C:/Program Files/Java/jdk1.6.0/bin/java -mx300m -classpath B.txt > sample-output.txt");
BufferedReader in =new BufferedReader(new InputStreamReader(pp.getErrorStream()));
String line;
while ((line = in.readLine()) != null)
System.out.println(line);
int exitVal = pp.waitFor();
System.out.println("Process exitValue: " + exitVal);
catch (Exception e)
e.printStackTrace();
System.out.println(e.getMessage());
} It compiles well but gives exception NoClassDefFound when I use java command to interpret it.Can u help?
Edited by: kimskams on Jun 29, 2008 7:24 AM -
Running OpenSSL command through Java Program
How do I execute openssl commands through a java program? Any packages or wrapper classes are there? Please help.
Thanks.Hi!
What do you mean execute commands? Like: "openssl x509 -in cert.pem -out certout.pem" ??
In that case you can just try the following:
import java.lang.Runtime;
try {
Runtime.getRuntime().exec("openssl x509 -in cert.pem -out certout.pem");
}catch (Exception e) {
e.printStackTrace();
........ -
Running windows command through java code
Hello
i want to execute jar.exe through java code , i have written following piece of code , but it isn't working
ProcessBuilder processBuilder = new ProcessBuilder(new String[]{"cmd.exe","/c","%java_home%\\bin\\jar.exe"});
Process process = processBuilder.start();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = inputReader.readLine();
while(line != null){
System.out.println(line);
line = inputReader.readLine();
does anybody knows why
Regards
Edited by: Mayur Mitkari on Mar 5, 2013 10:19 PM
Edited by: Mayur Mitkari on Mar 5, 2013 10:20 PM
Edited by: Mayur Mitkari on Mar 5, 2013 10:20 PMsorry for that , but the
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(new String[]{"cmd.exe","/c","jar"});
proc.waitFor();
int i = proc.exitValue();
this code was different from first one
and in case of Process if runtime .exec is succesful it is wainting for long time , in this case i want if the runtime.exec is succesful something should be returned
Regards
Maybe you are looking for
-
HT5625 multiple users on 1 computer and accessing
My household has multiple users on the computer. I downloaded while logged into my husband's iTunes. Now I can't update some of my apps because we can't access his password and his email he had used no longer exits. How can I transfer those apps t
-
Why is my MacBook Pro so slow?!
I made an Etrecheck, but I am not able to interpret the results... Some help would be greatly appreciated. Thanks! Hardware Information: MacBook Pro (13-inch, Mid 2009) MacBook Pro - model: MacBookPro5,5 1 2.26 GHz Intel
-
Which is better, the Hip-E, or the Mega PC Series?
A new computer was released last week that takes aim directly at kids. It's called the Hip-E, and you can check it out here: http://www.hip-e.com So, the question is, which do you like better the Mega PC or the Hip-E. (assuming both work perfectly
-
Send picture to exe application
Hi, all I'm now doing a project which have to send picture or frame in mc to external exe application and let it save those picture into jpg or other supported format. Is this possible to make ? Regards, Mephisto
-
The selection tool won't let me resize objects. I have read different forums where they all say I just have to show bounding box, but not even this works. I have been using Illustrator for a long time and never had this problem before. Please help me