Strange behaviour of Runtime.getRuntime().exec(command)
hello guys,
i wrote a program which executes some commands in commandline (actually tried multiple stuff.)
what did i try?
open "cmd.exe" manually (administrator)
type "echo %PROCESSOR_ARCHITECTURE%" and hit enter, which returns me
"AMD64"
type "java -version" and hit enter, which returns me:
"java version "1.6.0_10-beta"
Java(TM) SE Runtime Environment (build 1.6.0_10-beta-b25)
Java HotSpot(TM) 64-Bit Server VM (build 11.0-b12, mixed mode)"
type "reg query "HKLM\SOFTWARE\7-zip"" returns me:
HKEY_LOCAL_MACHINE\SOFTWARE\7-zip
Path REG_SZ C:\Program Files\7-Zip\
i wrote two functions to execute an command
1) simply calls exec and reads errin and stdout from the process started:
public static String execute(String command) {
String result = "";
try {
// Execute a command
Process child = Runtime.getRuntime().exec(command);
// Read from an input stream
InputStream in = child.getInputStream();
int c;
while ((c = in.read()) != -1) {
result += ((char) c);
in.close();
in = child.getErrorStream();
while ((c = in.read()) != -1) {
result += ((char) c);
in.close();
} catch (IOException e) {
return result;
}the second function allows me to send multiple commands to the cmd
public static String exec(String[] commands) {
String line;
String result = "";
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
// launch EXE and grab stdin/stdout and stderr
try {
Process process;
process = Runtime.getRuntime().exec("cmd.exe");
stdin = process.getOutputStream();
stderr = process.getErrorStream();
stdout = process.getInputStream();
// "write" the parms into stdin
for (int i = 0; i < commands.length; i++) {
line = commands[i] + "\n";
stdin.write(line.getBytes());
stdin.flush();
stdin.close();
// clean up if any output in stdout
BufferedReader brCleanUp = new BufferedReader(
new InputStreamReader(stdout));
while ((line = brCleanUp.readLine()) != null) {
result += line + "\n";
brCleanUp.close();
// clean up if any output in stderr
brCleanUp = new BufferedReader(new InputStreamReader(stderr));
while ((line = brCleanUp.readLine()) != null) {
result += "ERR: " + line + "\n";
brCleanUp.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return result;
}so i try to execute the commands from above (yes, i am using \\ and \" in java)
(1) "echo %PROCESSOR_ARCHITECTURE%"
(2) "java -version"
(3) "reg query "HKLM\SOFTWARE\7-zip""
the first function returns me (note that ALL results are different from the stuff above!):
(1) "" <-- empty ?!
(2) java version "1.6.0_11"
Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing)
(3) ERROR: The system was unable to find the specified registry key or value.
the second function returns me:
(1) x86 <-- huh? i have AMD64
(2) java version "1.6.0_11"
Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing)
(3) ERROR: The system was unable to find the specified registry key or value.
horray! in this version the java version is correct! processor architecture is not empty but totally incorrect and the reg query is still err.
any help is wellcome
note: i only put stuff here, which returns me strange behaviour, most things are working correct with my functions (using the Runtime.getRuntime().exec(command); code)
note2: "reg query "HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0" /t REG_SZ" IS working, so why are "some" queries result in ERR, while they are working if typed by hand in cmd.exe?
ok, i exported a jar file and execute it from cmd:
java -jar myjar.jar
now the output is:
(1) "" if called by version 1, possible to retrieve by version 2 (no clue why!)
(2) "java version "1.6.0_10-beta"
Java(TM) SE Runtime Environment (build 1.6.0_10-beta-b25)
Java HotSpot(TM) 64-Bit Server VM (build 11.0-b12, mixed mode)"
(3) C:\Program Files\7-Zip\
so all three problems are gone! (but its a hard way, as i need both functions and parse a lot of text... :/ )
thanks for the tip, that eclipse changes variables (i really did not knew this one...)
Similar Messages
-
hi, i am trying to run a NET USE command through using:
Runtime.getRuntime().exec(Command);
where Command is a valid NET USE command. I know it is valid because i executed this exact command
from the command line and it worked fine. This class works perfectly under Windows, but then i took it to an
OS/2 environment and i am getting this error. Does anybody know what i need to do to modify so it will work
under OS/2? any gotchas? thanksi read that article, and there is a lot to go over. I will start that right now. Anyways, i got the actual stack trace
from this error:
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:67)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Runtime.java:566)
at java.lang.Runtime.exec(Runtime.java:428)
at java.lang.Runtime.exec(Runtime.java:364)
at java.lang.Runtime.exec(Runtime.java:326)
at ReconnectReportServer.run(ReportServer.java:499)
at java.lang.Thread.run(Thread.java:536)
and, once again, i am running this on OS/2. I compiled it on OS/2 as well. Any ideas? thanks! -
Weird behaviour with Runtime.getRuntime.exec() attempting to start IE
I have developed a sample scheduler that it a web page the user fill in and then create a process schedule by the Timer class. The process starts IE in order to automate data entry normally done by a user. The Java code run well but IE when start from the p = Runtime.getRuntime().exec() class freeze. Is anyone can tell if IE require special setting to run in background?
Here the Java code but once again it work well but IE freeze and cause the forked process to hang.
// The schedule task
public void scheduleTask(Object o) throws ApplicationException {
ScheduleBean sb = (ScheduleBean)o;
try {
Timer timer = new Timer(true);
RunReslotting rr = new RunReslotting();
timer.schedule(rr, sb.getSchedulingDate());
catch(IllegalArgumentException iae) {
throw new ApplicationException(iae.getMessage());
catch(IllegalStateException ise) {
throw new ApplicationException(ise.getMessage());
public class RunReslotting extends TimerTask {
protected RunReslotting() {
public void run() {
String[] cmdLineParam = transportProfile(2);
cmdLineParam[0] = "location=" + wr.getLocation();
cmdLineParam[1] = "loc_class=" + wr.getNewStrategy();
forkProcess("runie.bat", cmdLineParam);
private String[] transportProfile(int startAt) {
envProf = System.getenv();
profCmd = new String[envProf.size() + startAt];
itr = envProf.entrySet().iterator();
int i = startAt;
while (itr.hasNext()) {
entry = (Map.Entry)itr.next();
profCmd[i] = (String)entry.getKey() + "=" + (String)entry.getValue();
i++;
return profCmd;
private void forkProcess(String processName, String[] osParam) throws ApplicationException {
// Lance un nouveau process
p = null;
int i=0;
try {
p = Runtime.getRuntime().exec(processName, osParam);
// Vide les buffers du process pour eviter de geler
mcError = new MessageCatcher(p.getErrorStream());
mcOutput = new MessageCatcher(p.getInputStream());
mcError.start();
mcOutput.start();
i = p.waitFor();
if ( (i != 0) || (mcError.getMessage() != null) || (mcOutput.getMessage() != null) ) {
System.err.println("*** Process failed RC:" + i + " *** ");
if (mcOutput.getMessage() != null) {
System.err.println("Output messages: " + mcOutput.getMessage());
if (mcError.getMessage() != null) {
System.err.println("Error messages: " + mcError.getMessage());
throw new ApplicationException("*** Process failed *** ");
catch(IOException ioe) {
throw new ApplicationException(ioe.getMessage());
catch(InterruptedException ie) {
throw new ApplicationException(ie.getMessage());
Any suggestion will be appreciate. I�m working on that scheduler for a while and i'm desperate
Thanks
FrancisThis starts IE for me, no problem
String[] cmd = {"C:\\Program Files\\Internet Explorer\\iexplore.exe"};
Runtime.getRuntime().exec(cmd); -
Runtime.getRuntime().exec(command)
I have to exec the keytool command from a server:
MY CODE:
String cmd = new String("/usr/local/j2sdkee/bin/keytool -genkey -dname \"cn="+nome+" "+cognome+", ou="+lavoro+", o="+impresa+", c="+stato+"\" -alias cert -keypass keypass -keystore /usr/local/server4/keystore/"+userid+" -storepass storepass -validity 180");
System.out.println("cmd = "+cmd);
Runtime rt = java.lang.Runtime.getRuntime();
Process ksGenerator = null;
ksGenerator = rt.exec(cmd);
ksGenerator.waitFor();
System.out.println("exitValue "+ksGenerator.exitValue());
PROBLEM:
The exit Value is correct (=0) and there isn't any exception .... but the command didn't work...
If i try to exec the command from shell it work.
How can i do???
THANKSSomeone in another forum suggested that one should ALWAYS use the exec command that takes an array of arguments, rather than a single string.
-
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 -
Running curl command from a java program using Runtime.getRuntime.exec
for some reason my curl command does not run when I run it from within my java program and errors out with "https protocol not supported". This same curl command however runs fine from any directory on my red hat linux system.
To debug the problem, I printed my curl command from the java program before calling Runtime.getRuntime.exec command and then used this o/p to run from the command line and it runs fine.
I am not using libcurl or anything else, I am running a simple curl command as a command line utility from inside a Java program.
Any ideas on why this might be happening?thanks a lot for your response. The reason why I am using curl is because I need to use certificates and keys to gain access to the internal server. So I use curl "<url> --cert <path to the certificate>" --key "<path to the key>". If you don't mid could you please tell me which version of curl you are using.
I am using 7.15 in my system.
Below is the code which errors out.
public int execCurlCmd(String command)
String s = null;
try {
// run the Unix "ps -ef" command
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// 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);
return(0);
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
return(-1);
} -
Runtime.getRuntime().exec problems
i am trying to run files from my java application, i use the following command
Runtime.getRuntime().exec("cmd /c start " + filePath);but it seems that it cant handle file path with spaces, like
C:\Documents and Settings\Administrator\My Documents\My Web\Untitled-3.fla
it works well with path like this
C:\Downloads\1.rar
am i right? and how to solve this problem? thanksfinal String[] command =
"cmd.exe",
"/C",
"start \"" + filename + "\"",
final Process p = Runtime.getRuntime().exec(command);this method can only trigger files in the same folder as the java application, isnt it? -
Runtime.getRuntime.exec() may hang?
Hi, I am trying to run a Microsoft application, suspend.exe, under Java, on xp. I noticed that sometimes the program would hang, after issuing the command.
String command = "cmd /c suspend.exe -n 15 -s 3 -l c:\\scpt\\s3.txt -e " ;
suspend = Runtime.getRuntime().exec (command);
Is there a compatibility between MS and Java after Java releases the control to the native environment? Has anyone seen this? Sometimes this gets kicked off, and sometimes it doesn't.
* I am really confused. Thanks for any helpthank you, I will look into this.
Btw, do you know how to start a java program at start up? I have searched and read some articles, but none seems to do the trick for me.
I have:
1) create a bat file. This bat file runs fine w/ double clicking, but when trying to place it in startup folder and run it, it quits.
2) create a simple c vesion of .exe file. This possesses the same behavior as above
3) create a short cut to the bat file and place it in startup folder. Nothing happens.
4) add reg. key in regedit with
'java Pclient'
and
'java c:\scpt\Pclient'
nothing seems to happen.
still searching...
thank you. -
Runtime.getRuntime().exec() does not return
Hello,
I am running into a case where the call to Runtime.getRuntime.exec(command) does not return. The scenario is that the main thread spawns another thread which calls the Runtime.exec(). Since the call does not return, both threads seems to be hung. The jstack output from the main thread shows
----------------- t@2 -----------------
0xfeedab45 ___lwp_cond_wait + 0x15
0xfeb4030d void os::PlatformEvent::park() + 0xa9
0xfebadd48 void ObjectMonitor::wait(long long,bool,Thread*) + 0x26c
0xfe770287 void ObjectSynchronizer::wait(Handle,long long,Thread*) + 0xef
0xfe76ffbb JVM_MonitorWait + 0x20f
0xfb20a032 * java.lang.Object.wait(long) bci:0 (Interpreted frame)
0xfb20308d * java.lang.Thread.join(long) bci:38 line:1143 (Interpreted frame)
0xfb20308d * java.lang.Thread.join() bci:2 line:1196 (Interpreted frame)
0xfb20308d * DataLoader.checkThreadGroup() bci:92 line:316 (Interpreted frame)
0xfb202f27 * DataLoader.checkTables(int) bci:1 line:336 (Interpreted frame)
0xfb202f69 * DataLoader.runLoad(int, java.lang.String, java.lang.String, java.lang.String, com.sabre.fltsked.apm.util.FSIOHelper)
... more below ....
So it is waiting for the spawned thread on a join()
And the jstack dump for the thread that called exec() is
----------------- t@70 -----------------
0xfeed7409 __lwp_park + 0x19
0xfeed1be7 cond_wait_queue + 0x5e
0xfeed1f64 cond_wait_common + 0x1db
0xfeed20d2 condwait + 0x7b
0xfeed20fd cond_wait + 0x21
0xfeed2136 pthread_cond_wait + 0x1b
0x9741082a soft_delete_object_cleanup + 0x57
0x97410906 soft_delete_object + 0x5b
0x97410953 soft_delete_all_objects_in_session + 0x2e
0x97407b7a soft_delete_session + 0xec
0x97407860 soft_delete_all_sessions + 0x3c
0x97402525 finalize_common + 0x66
0x974026ae softtoken_fini + 0x34
0x974355f9 _fini + 0x21
0xfefdd49a remove_hdl + 0x766
0xfefd8be9 dlclose_core + 0xb1
0xfefd8c1d dlclose_intn + 0x21
0xfefd8c96 dlclose_check + 0x2a
0xfefd8d00 dlclose + 0x38
0x97480aeb pkcs11_slottable_delete + 0xb1
0x9747c691 finalize_common + 0xe2
0x9747c6e0 pkcs11_fini + 0x3e
0x9747c3bf pkcs11_fork_child + 0x73
0xfee628b8 postforkchild_handler + 0x2f
0xfeeca9ec fork + 0x12e
0xfe338029 Java_java_lang_UNIXProcess_forkAndExec + 0x395
0xfb20a032 * java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) bci
:0 (Interpreted frame)
0xfb202f69 * java.lang.UNIXProcess.<init>(byte[], byte[], int, byte[], int, byte[], boolean) bci:62 line:53 (Interpreted frame)
0xfb20308d * java.lang.ProcessImpl.start(java.lang.String[], java.util.Map, java.lang.String, boolean) bci:182 line:65 (Interpreted frame)
0xfb202f27 * java.lang.ProcessBuilder.start() bci:112 line:452 (Interpreted frame)
0xfb202f27 * java.lang.Runtime.exec(java.lang.String[], java.lang.String[], java.io.File) bci:16 line:593 (Interpreted frame)
0xfb202f27 * java.lang.Runtime.exec(java.lang.String, java.lang.String[], java.io.File) bci:69 line:431 (Interpreted frame)
0xfb202f27 * java.lang.Runtime.exec(java.lang.String) bci:4 line:328 (Interpreted frame)
0xfb202f27 *SQLLoad(java.lang.StringBuffer) bci:181 line:51 (Interpreted frame)
0xfb202e61 *FSLoadThread.run() bci:84 line:54 (Interpreted frame)
The command I am trying to exec is "sqlldr" and I do have it in my PATH variable. Why is that the call to exec does not return? Any ideas?
This is on jdk1.6.0_17
Thanks,
Bijoy.It has definitely forked, and this is the child process. It says so. If it was the parent process it would just show Java code related to launching processes. That does not involve PKCS11. After the fork there are two identical processes with the same stack: the child process of the fork goes on to replace itself with the target command via Unix exec(), which it doesn't look like it is succeeding at. The parent process doesn't do much at all, probably just housekeeping and then a Unix wait() for Process.waitFor() to hook into.
-
Runtime.getruntime.exec() getOutputStream()
Hi,
can anyone tell me what this is used for?
i though i maybe could use it in this example
exec(cmd /c start)
out.write("dir".getBytes());
but that doesn't seem to work?
also does anyone know like if i want to start a cmd and want to keep that open and do multiple commands like first cd then dir
i thought u could with the ouputstream, but that isn't right? or am i wrong?
thanks in advanceYou need something like
String[] command =
"cmd",
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("dir c:\\ /A /Q");
// write any other commands you want here
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);where SyncPipe is a runnable in which the run() method copies the content of the InputStream to the OutputStream. You can use StreamGobbler instead.
Note - commands sent to the stdin of cmd.exe need to be terminated by a new line. When you have finished all input you should close stdin.
Note 1 - since the string "dir c:\\ /A /Q") is interpreted by cmd.exe you MUST use the \ char as a file separator. -
Runtime.getRuntime().exec works on windows failed on linux!
Hi,
I'm trying to execute a linux command from java 1.4.2 using Runtime.getRuntime().exec(). The linux command produces output and write to a file in my home dir. The command runs interactively in the shell and also run on windows.
The command is actually a mozilla pk12util. My java code to run this pk12util works on windows, but not on linux (fedora). When I print out the command I'm trying to run in java, I can run it interactively in bash shell.
Method below is where the problem seems to be:
public void writeCert() {
// Declaring variables
System.out.println("Entering writeCert method");
String command = null;
certFile = new File(credFileName);
// building the command for either Linux or Windows
if (System.getProperty("os.name").equals("Linux")) {
command = linuxPathPrefix + File.separator + "pk12util -o "
+ credFileName + " -n \"" + nickName + "\" -d "
+ dbDirectory + " -K " + slotpw + " -w " + slotpw + " -W "
+ pk12pw;
System.out.println("System type is linux.");
System.out.println("Command is: " + command);
if (System.getProperty("os.name").indexOf("Windows") != -1) {
// command = pk12utilLoc + File.separator + "pk12util -o
// "+credFileName+" -n "\"+nickname+\"" -d \""+dbDirectory+"\" -K
// "+pk12pw+" -w "+pk12pw+" -W "+pk12pw;
command = pk12utilLoc + File.separator + "pk12util.exe -o "
+ credFileName + " -n \"" + nickName + "\" -d "
+ dbDirectory + " -K " + slotpw + " -w " + slotpw + " -W "
+ pk12pw;
System.out.println("System type is windows.");
System.out.println("Command is: " + command);
// If the system is neither Linux or Windows, throw exception
if (command == null) {
System.out.println("command equals null");
try {
throw new Exception("Can't identify OS");
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
// Having built the command, running it with Runtime.exec
File f = new File(credFileName);
// setting up process, getting readers and writers
Process extraction = null;
BufferedOutputStream writeCred = null;
// executing command - note -o option does not create output
// file, or write anything to it, for Linux
try {
extraction = Runtime.getRuntime().exec(command);
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
// Dealing with the the output of the command; think -o
// option in command should just write the credential but dealing with output anyway
BufferedWriter CredentialOut = null;
OutputStream line;
try {
CredentialOut = new BufferedWriter (
new OutputStreamWriter(
new FileOutputStream(credFileName)));
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
// writing out the output; currently having problems because I am trying to run
}My error is due to the nickname "-n <nickname" parameter error. I think the problem is having a double quotes around my nickname, but if I take out the double quotes around my nickname "Jana Test's ID" won't work either because there are spaces between the String. Error below:
Command is: /usr/bin/pk12util -o jtest.p12 -n "Jana Test's Development ID" -d /home/jnguyen/.mozilla/firefox/zdpsq44v.default -K test123 -w test123 -W test123
Read from standard outputStreamjava.io.PrintStream@19821f
Read from error stream: "pk12util: find user certs from nickname failed: security library: bad database."
null
java.lang.NullPointerException
at ExtractCert.writeCert(ExtractCert.java:260)
at ExtractCert.main(ExtractCert.java:302)
Code is:
private String nickName = null;
private void setNickname(String nicknameIn) {
nickName = nicknameIn;
// building the command for either Linux or Windows
if (System.getProperty("os.name").equals("Linux")) {
command = linuxPathPrefix + File.separator + "pk12util -o " + credFileName + " -n \"" + nickName + "\" -d " + dbDirectory + " -K " + slotpw + " -w " + slotpw + " -W " + pk12pw;
System.out.println("System type is linux.");
System.out.println("Command is: " + command);
extraction = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(
new
InputStreamReader(extraction.getErrorStream()));
PrintStream p = new PrintStream(extraction.getOutputStream());
System.out.println("Read from standard outputStream" + p); -
Runtime.getRuntime().exec - relies on the J2RE?
Well here is a problem...
My program works fine using the Runtime.getRuntime().exec command, and the program works as-intended on my computer. But that's because I have the latest and greatest Java apparel (especially the J2RE).
Now, a friend of mine who does not program, took my program and tried it on his computer. It worked (the GUI loaded and buttons functioned) but it didn't actually do anything other than serve as a nice-looking GUI lol.
The problem was, it was creating the file I had it create (using FileWriter) but it wasn't EXECUTING that file like I designed the program to.
I used the Runtime.getRuntime().exec to execute the file - my question is, if the person doesn't have the Java Runtime Environment, will that command work? He clearly has Java on his computer (the GUI loaded) but he might not have the J2RE...
Any thoughts? Any suggestions for an alternative way to execute a file?
Thanks!
-JoshI don't understand why this wont work on other
people's computers...
I create the file "commands.bat" in their C:\
directory. I then have the following command to
execute it:
Runtime.getRuntime().exec("cmd.exe /c
\"C:\\crasher.bat\"");It works perfect for me... But it doesn't work for
other people. For other people, it creates the batch
file in the right place, it just wont execute it and
I am not sure why...
-JoshYou said "commands.bat" but your code is executing "crasher.bat". I have the feeling you're trying to crash their computers or something?
cmd.exe is an executable on certain flavors of Windows. Other flavors of Windows have command.exe, not cmd.exe. So you have to pick the same platform, or make the actual command that you execute be dynamic (read it from a property file to determine what to execute).
Go to those other machines and see if you can execute that same command from the command line. Do some debugging for pete's sake. -
Problem with Runtime.getRuntime().exec
Hi ,
i'm using jBuilderX and windows 2000 server . My problem is that i can't
find why
in my code it doesn't work this:
import java.lang.*;
String command = new String("c:\\testd\\testf.bat"); // testf.bat -
batch file
Runtime.getRuntime().exec(command); // it doesn't
have any effect
Thanks in advance,What's it supposed to do?
I can definitely help you on this 1, but I'd really like to see your streamoutputs. You can get these from the Process object that is created, but you'll need to add some threaded listeners to get the data.
Is this possible? -
Using Process Runtime.getRuntime().exec
http://im1.shutterfly.com/procserv/47b4d633b3127cceb46774c84ee80000001610
Here is a URL to a part of the current process I need to run. Actually there are 4 steps that preceed these but they are ran in order and must be done before these (that part is easy). Sorry it kinda chopped off the left side a little bit.
My question is, can I do this entirely using Runtime.getRuntime().exec() commands or do I need to involve multi threading. The reason I am asking is because P13 cannot run until P8 and P9 completes, but that shouldn't stop the rest of the program from running.
If I have something like
Process P4 = Runtime.getRuntime().exec(P4);
Process P5 = Runtime.getRuntime().exec(P2);
// Some handling for the streams of these processes goes here
P4.waitFor();
P2.waitFor();
if(P2.exitValue() != 0){
Process P5 = Runtime.getRuntime().exec(P5);
Process P6 = Runtime.getRuntime().exec(P6);
// Some handling for the streams of these processes goes here
Does that mean the whole program will stop and wait until P4 is done before even checking for P2? If P2 is finished would the program continue and run P5 and P6 even if P4 is still running or will it wait for P4 to complete also. P4 has nothing to do with P2?
Also any advice ???P4 and P2 will both be running in parallel (or as much as your OS and hardware allows them to be). As soon as both are done, and regardless of which finishes first, whatever follows P2.waitFor() will execute.
If you have multiple groups of processes, where the processes within a group must execute sequentially, but the groups themselves can run independently of each other, then you'll need to either use Java's threads, or wrap each group of sequential processes in a shell script or batch file the executes that group sequentially.
If there are complex dependencies among the groups--that is, multiple groups must wait on the same process, or one group must wait for multiple other groups, then it might be easier to control the concurrency in Java. -
Runtime.getRuntime().exec(x) "Command not found"?
Hello,
I am attempting to run the following code in my java program.
System.out.println("<!> gunzip -c " + curZippedFilePath + " | tar xf - --directory " + curMovedUnzippedPath;
String unzipCommand[] = {"sh gunzip -c " + curZippedFilePath + " | tar xf - --directory " + curMovedUnzippedPath};
Process unzipChild = Runtime.getRuntime().exec(unzipCommand);
However, when it is run, I get the following message.
<!> gunzip -c /gnm/apache/htdocs/GNM_Data/1c02.tgz | tar xf - --directory /gnm/GNM_Autoupdate/databaseUpdate/dataDump/1c02
Exception in thread "main" java.io.IOException: java.io.IOException: gunzip -c /gnm/apache/htdocs/GNM_Data/1c02.tgz | tar xf - --directory /gnm/GNM_Autoupdate/databaseUpdate/dataDump/1c02: not found
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:464)
at DatabaseBackUpdate.main(DatabaseBackUpdate.java:49)Why is the gunzip command not found? Also, the command works when I try it in the shell. Why doesn't it work in the Java code?I got it!
I needed to use the following without passing an array to the exec() function.
String theCommand = "tar xfz " + curZippedFilePath + " -C " + dataDumpDir;
Process unzipChild = Runtime.getRuntime().exec(theCommand);No onto another problem : (
Maybe you are looking for
-
I have a problem with a query that includes 5 tables! Equipment ec, (ec.cost, ec.workid) Material mc, (mc.cost, mc.workid) Labor lc, (lc.cost, lc.workid) Work wo, (wo.workid) Entity en The primary key is the work id The columns I need to extract are
-
Payments are going in two separate for one account
The payment for vendors in Payment Proposal (F110) are going in two separate transactions for once account. Say for vendor 1011274 the payment amount should be 741 whereas the payment is going in two separate transactions (two payment documents) of
-
UCCX 9.0(2) XML question
I'm teaching myself about SOAP and XML responses for an upcoming project for a self-service application. We have UCCE/ICM UCCX/IPIVR premium licenses. I used the excellent article by Gergely (https://supportforums.cisco.com/document/97736/uccx-8x-rea
-
In the browser Chrome, after going to a website starting with https://, it gave me the below message: Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure resource 'http://...'. This request has been blocked; the
-
I'm getting an error when i try to access a page with spring taglibs. During the deploy there are not any error. Error: personAdd.jsp:2:5: No tag library could be found with this URI. Possible causes could be that the URI is incorrect, or that there