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...
Similar Messages
-
How to execute dos command in Java program?
In Perl, it has System(command) to call dos command.
Does java have this thing?
or any other way to execute dos command in java program?
Because i must call javacto compile a file when the user inputed a java file name.Look in the Runtime class, it is implemented using the Singleton design pattern so you have to use the static method getRuntime to get its only instance, on that instance you can invoke methods like
exec(String command) that will execute that command in a dos shell.
Regards,
Gerrit. -
EXECUTE DOS COMMANDS WITH JAVA
I'm new to java and I want to execute dos commands by java
can someone help me by by anyway?
like tell me the packages or methods I need
or give me links to sites?
thanksNo Arguments:
try {
// Execute a command without arguments
String command = "ls";
Process child = Runtime.getRuntime().exec(command);
// Execute a command with an argument
command = "ls /tmp";
child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
}With Arguments:
try {
// Execute a command with an argument that contains a space
String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};
commands = new String[]{"grep", "hello world", "c:\\Documents and Settings\\f.txt"};
Process child = Runtime.getRuntime().exec(commands);
} catch (IOException e) {
} -
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. -
How to execute DOS command in Java?
I want to execute a dos command in Java,such as execute test.bat command? How to realize it?
Thanks in advance!http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
I found this article really useful in solving this. Hope it helps.
Cheers,
John -
Execute DOS command inside java
I have a java program that reads each new user from an inputfile and writes that same user to an output file. The program works fine and is shown below:
import java.io.*;
public class FileStreamsTest {
public static void main(String[] args) {
try {
File inputFile = new File("newbousrs.txt");
File outputFile = new File("outagain.txt");
FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
int c;
while ((c = fis.read()) != -1) {
fos.write(c);
fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsTest: " + e);
} catch (IOException e) {
System.err.println("FileStreamsTest: " + e);
What I would like to do after each write is to execute a DOS command that looks something like this: supervsr.exe -USER username -PASS password -IMPORTUSERS importfile.txt
The DOS command above will add each user to the system I want to as the loop goes through each user record.
How do I execute the DOS command above inside java?Tried what but still having a problem...here is my code:
import java.io.*;
public class ReadSource {
public static void main(String[] arguments) {
try {
FileReader file = new FileReader("newbousrs.txt");
//FileWriter letters = new FileWriter("outagain.txt");
//PrintWriter pw = new PrintWriter(new FileWriter("outagain.txt"));
BufferedReader buff = new BufferedReader(file);
Runtime rt = Runtime.getRuntime();
boolean eof = false;
while (!eof) {
String line = buff.readLine();
if (line == null)
eof = true;
else
System.out.println(line);
Process proc = rt.exec("\\Blowfish\\droot\\Program Files\\Business Objects\\BusinessObjects 5.0\\supervsr.exe -USER xxxxx -PASS yyyy -IMPORTUSERS \\Blowfish\\droot\\accsp\\public\\newusers\\newbousrs.txt");
//System.out.println(line.substring(4, 10));
//System.out.println(line.substring(3,line.indexOf(',',3)));
buff.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
There error I get is this:
C:\jakarta-tomcat-4.0.3\webapps\webdav\WEB-INF\classes\accsp>java ReadSource
NU,Public,Steve Mcnealy,Steve Mcnealy,U,N,N,Y,N,N,PC,F,Y,N,N
Error -- java.io.IOException: CreateProcess: \Blowfish\droot\Program Files\Busin
ess Objects\BusinessObjects 5.0\supervsr.exe -USER accsp -PASS fish -IMPORTUSERS
\Blowfish\droot\accsp\public\newusers\newbousrs.txt error=3 -
Execute DOS command from java application
Hello,
I want to execute a DOS command (MOVE, in order to move an image from a folder to an other) from a java application. How can I do this?
FrancescoYes I have tested it and it is working but only when executing a bacth file. For instance:
Runtime rt = Runtime.getRuntime();
try{
Process proc = rt.exec("move.bat");
}catch(Exception ex){
ex.printStackTrace();
}and the command in move.bat is:
move c:\\temp\\*.gif C:\\temp2
You don't have to use double slashes in batch files, only in Java. But anyway it is working both ways.
It is not working when you try to execute the command without the batch file:
Process proc = rt.exec("move c:\\temp\\*.gif C:\\temp2"); -> this will not work.
It should work. Try to execute another command to see what happens. -
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. -
Execute DOS command from Java Code
Hi All
I am developing a Java application where I am launching some external Windows application on click event of a button.
I am able to launch that application, but now I have to keep a check that if once that application is launched on clicking the button, then next time it should not launch. But if user exits that external application, then on clicking the button that application should be launched. I tried several ways but i am not able to keep track of that process which makes that application run. The major problem is that when that application is being launched and running, i don't have anything to read or write to that process's Input Stream or Output Stream. Can any one help me out in this????ApratimSharma wrote:
You Might not get anything in the inputstream.read but when the external application will exit you will definitely get EOF (int -1). However Important thing here is that inputstream.read is a blocking call so better do it in a separate thread.
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("calc");
InputStream inputStream = process.getInputStream();
if (inputStream != null) {
System.out.println("Running");
while (inputStream.read() != -1);
System.out.println("Exited");
} catch (Exception e) {
e.printStackTrace();
}Now that is what I call 'stating the obvious' !
You need to read the 4 sections of [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html] and implement ALL the recommendations.
Edited by: sabre150 on Oct 8, 2009 10:00 AM -
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 -
Help with executing windows command in java
hi, i am trying to execute dos command in java. currently i am trying simply to create a folder in the current directory.
here is the code snippet:
try {
Process p = Runtime.getRuntime().exec("md myFolder");
} catch (IOException io) {
io.printStackTrace();
i have also tried using "mkdir" instead of "md". but my code just throws an exception that says:
java.io.IOException: CreateProcess: md myFolder error=2
what have I done wrong? thanks in advancetry {
Process p = Runtime.getRuntime().exec("cmd /c
mkdir myFolder");
catch (IOException io) {
io.printStackTrace();hey! that code worked out perfectly. so "cmd" is needed to run dos commands? i searched through the net, but most of the examples that i were able to find did not include "cmd".
if it wouldn't be too much trouble, what is the option "/c" for?
i would also like to add that "mkdir" also works. The problem was the missing "cmd /c". Thanks guys for your help! I really appreciate it. -
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");
************************************************************************************************************************************** -
How to execute Dos Command 'Pause' from Java ?
How to execute Dos Command 'Pause' from Java ?
I have read the article in javaworld for Runtime.exec() anomalies.
Can someone please give an insight on this?Thanks Buddy!
That was very useful. Even though its a simple
solution, I never thought about that.Bullshit! Reread reply #7 of http://forum.java.sun.com/thread.jspa?threadID=780193 -
Hi all,
Is it possible to execute a DOS command in java? If so, how do I do that?
Also, if it is a Linux machine, may I execute a Linux command in java?
Thanks for your help.
Regards,
BernardFirst, define 'command'.
You can run external programs with Runtime.exec (eg. Runtime.getRuntime().exec("notepad");) but there are a few drawbacks regarding that method.
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html -
Can we execute DOS Commands from a Java Application
I just want to know whether we can execute DOS Commands from a Java Application.
Thanks.hi,
try this:
Runtime.getRuntime().exec("cmd /c start abc.bat");
andi
Maybe you are looking for
-
Hello, I can't find my loops! I have GB2 and an iMac G5 and my loops are not showing up in the loop browser. I still have the folder with all the loops in it, however, when I try to drag it into the loop browser, nothing happens. The computer says th
-
Ok, I have searched for months for an answer to this question to no avail, probably because no one has experienced it before. I am hoping however that you guys can help me figure this one out cause it is driving me nuts! Also, I am not entirely sure
-
Hi, I have a customized SharePoint page that takes user input data, validate some of the data, then writes the data to a SharePoint list. If an exception occurs, it will write the error to the ULS. All was working well in the test environments. Howev
-
Mini Bridge will not load in PSC5
When I'm in photoshop cs5, and click on mini-bridge, it says it can't load. Same with any other extenions I have. I've uninstalled the program. Used MAC keeper, which is supposed to remove everything. But I reinstall CS5, said it was installed, ev
-
Hello all, My beautiful 1 year old daughter pull my nano off a Bose speaker dock and ever since the wheel and buttons have been non-responsive. I've tried a rest and all troubleshooting steps with no luck. Does anyone out there have any other sugge