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.

Similar Messages

  • 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

  • How to execute system command from java program

    Hi all,
    I want to change directory path and then execute bash and other unix commands from a java program. When I execute them separately, it's working. Even in different try-catch block it's working but when I try to incorporate both of them in same try-catch block, I am not able to execute the commands. The change directory command works but it won't show me the effects of the bash and other commands.
    Suggestions??

    The code I am using is....
    try
    String str="cd D:\\Test";
    Process p=Runtime.getRuntime().exec("cmd /c cd
    "+str);your str string is already having cd in it but again you ar giving cd as part of this command also please check this,i will suggest you to remove cd from str
    Process p1=Runtime.getRuntime().exec("cmd /c mkdir
    "+str+"\\test_folder");you should say mkdir once you change your path,but here you are saying mkdir first and then cd D:\Test(this is because of str)..please check this
    Process p2=Runtime.getRuntime().exec("cmd /c bash");
    Process p3=Runtime.getRuntime().exec("cmd /c echo
    himanshu>name.txt");
    catch(IOException e)
    System.err.println("Error on exec() method");
    e.printStackTrace();
    Message was edited by:
    ragas

  • 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

  • How to execute Linux command from Java app.

    Hi all,
    Could anyone show me how to execute Linux command from Java app. For example, I have the need to execute the "ls" command from my Java app (which is running on the Linux machine), how should I write the codes?
    Thanks a lot,

    You can use "built-in" shell commands, you just need to invoke the shell and tell it to run the command. See the -c switch in the man page for your shell. But, "ls" isn't built-in anyays.
    If you use exec, you will want to set the directory with the dir argument to exec, or add it to the command or cmdarray. See the API for the variants of java.lang.Runtime.exec(). (If you're invoking it repeatedly, you can most likely modify a cmdarray more efficiently than having exec() decompose your command).
    You will also definitely want to save the returned Process and read the output from it (possibly stderr too and get an exit status). See API for java.lang.Process. Here's an example
    java.io.BufferedReader br =
    new java.io.BufferedReader(new java.io.InputStreamReader(
    Runtime.getRuntime().exec ("/sbin/ifconfig ppp0").
    getInputStream()));
    while ((s = br.readLine()) != null) {...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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?
    thanks

    No 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) {
        }

  • 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...

  • Problem while running dos command from java program

    Dear friends,
    I need to terminate a running jar file from my java program which is running in the windows os.
    For that i have an dos command to find process id of java program and kill by using tskill command.
    Command to find process id is,
    wmic /output:ProcessList.txt process where "name='java.exe'" get commandline,processid
    This command gives the ProcessList.txt file and it contains the processid. I have to read this file to find the processid.
    when i execute this command in dos prompt, it gives the processid in the ProcessList.txt file. But when i execute the same command in java program it keeps running mode only.
    Code to run this command is,
    public class KillProcess {
         public static void main(String args[]) {
              KillProcess kProcess = new KillProcess();
              kProcess.getRunningProcess();
              kProcess = new KillProcess();
              kProcess.readProcessFile();
         public void getRunningProcess() {
              String cmd = "wmic /output:ProcessList.txt process where \"name='java.exe'\" get commandline,processid";
              try {
                   Runtime run = Runtime.getRuntime();
                   Process process = run.exec(cmd);
                   int i = process.waitFor();
                   String s = null;
                   if(i==0) {
                        BufferedReader stdInput = new BufferedReader(new
                               InputStreamReader(process.getInputStream()));
                        while ((s = stdInput.readLine()) != null) {
                         System.out.println("--> "+s);
                   } else {
                        BufferedReader stdError = new BufferedReader(new
                               InputStreamReader(process.getErrorStream()));
                        while ((s = stdError.readLine()) != null) {
                         System.out.println("====> "+ s);
                   System.out.println("Running process End....");
              } catch(Exception e) {
                   e.printStackTrace();
         public String readProcessFile() {
              System.out.println("Read Process File...");
              File file = null;
              FileInputStream fis = null;
              BufferedReader br = null;
              String pixieLoc = "";
              try {
                   file = new File("ProcessList.txt");
                   if (file.exists() && file.length() > 0) {
                        fis = new FileInputStream(file);
                        br = new BufferedReader(new InputStreamReader(fis, "UTF-16"));
                        String line;
                        while((line = br.readLine()) != null)  {
                             System.out.println(line);
                   } else {
                        System.out.println("No such file");
              } catch (Exception e) {
                   e.printStackTrace();
              return pixieLoc;
    }     when i remove the process.waitFor(), then while reading the ProcessList.txt file, it says "No such file".
    if i give process.waitFor(), then it's in running mode and program is not completed.
    Colud anyone please tell me how to handle this situation?
    or Is there anyother way to kill the one running process in windows from java program?
    Thanks in advance,
    Sathish

    Hi masijade,
    The modified code is,
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        public void run()
            try
                InputStreamReader isr = new InputStreamReader(is, "UTF-16");
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    System.out.println(type + ">" + line);
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    public class GoodWindowsExec
        public static void main(String args[])
            try
                String osName = System.getProperty("os.name" );
                String[] cmd = new String[3];
                 if( osName.equals( "Windows 95" ) )
                    cmd[0] = "command.com" ;
                    cmd[1] = "/C" ;
                    cmd[2] = "wmic process where \"name='java.exe'\" get commandline,processid";
                } else {
                    cmd[0] = "cmd.exe" ;
                    cmd[1] = "/C" ;
                    cmd[2] = "wmic process where \"name='java.exe'\" get commandline,processid";
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd[0] + " " + cmd[1]
                                   + " " + cmd[2]);
                Process proc = rt.exec(cmd);
                System.out.println("Executing.......");
                // any error message?
                StreamGobbler errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR");           
                          // any output?
              StreamGobbler outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT");
                          // kick them off
                errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            } catch (Throwable t)
                t.printStackTrace();
    }when i execute the above code, i got output as,
    Execing cmd.exe /C wmic process where "name='java.exe'" get commandline,processid
    and keeps in running mode only.
    If i execute the same command in dos prompt,
    CommandLine
    ProcessId
    java -classpath ./../lib/StartApp.jar;./../lib; com.abc.middle.startapp.StartAPP  2468
    If i modify the command as,
    cmd.exe /C wmic process where "name='java.exe'" get commandline,processid  > 123.txt
    and keeps in running mode only.
    If i open the file when program in running mode, no contents in that file.
    If i terminte the program and if i open the file, then i find the processid in that file.
    Can you help me to solve this issue?

  • How to run DOS command in Java environment?

    Can i run DOS command in Java environment?
    I did like this:
    Runtime r = Runtime.getRuntime();
    r.exec("cmd.exe");
    r.exec("set classpath=%CLASSPATH%;.\\tmp")
    but failed.
    However if I run the java command, it runs successfully.
    r.exec("javac Test.java");
    r.exec("java Test");
    how should I do so that i can run the DOS commands metioned above in Java Environment?
    thanks a lot.

    Have a look at http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    This may help. I wonder if this is ok ?
    Runtime r= Runtime.getRuntime();
    r.exec("cmd.exe /C set classpath=%CLASSPATH%;.\\tmp\"");

  • 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.).

  • 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?
    Francesco

    Yes 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.

  • How to execute .msi files from java program

    Hi friends,
    i have written a java program which invokes and thereby execute any executable files like .exe and .bat.
    So its working fine with .exe and .bat files, but it is not working with .msi files.......can you please help me how can i execute .msi files as well??
    public class Executeexe {
         public static void main(String ar[])
              try
              Process p=null;
              Runtime rt=Runtime.getRuntime();
              p=rt.exec("D:\\mysql-essential-5.0.83-win32.msi");
              p.waitFor();
    catch(Exception e)
    }here is the program

    Make sure that the command that's being exec'd works from the cmd line.
    Then read this article and do what it says:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Then if you still are having problems explain what "...it is not working with .msi files..." really means, and provide a [SSCCE Example program|http://mindprod.com/jgloss/sscce.html]

  • Execute Unix command from Java program running on windows

    Hello,
    I need to write a java program that fetches file count in a particular unix machine directory. But java program will be running on windows machine.
    The program should execute unix list command and fetch the output of that command.
    Can anyone help me on this?
    Thanks.

    Hi there,
    I had a similiar problem, though years ago. It was to have a java program execute any other. Lately, I've had to have a java program running on a unix machine execute a shell script. Entirely two different scenarios. I'm not sure what you will need for your app, but look into this:
    Java Native Interface for executing C/C++ code.
    C/C++ Code for launching the program you need to run.
    java.lang.Runtime(?).exec(....)
    With a combination of that stuff, you can make a launcher for any os that has Java running on it, and with Runtime, you can exec() pretty near any sort of unix shell or app command you'd like.
    Good luck.
    Tim

Maybe you are looking for

  • RAM slot dead - MBP 15 Mid 2010

    Hi guys, I was away from home for a week and my MBP was turned off for the whole time. As I got home and turned it on, not even 5 minutes had passed while I was checking my email and it rebooted on its own out of the blue. Problem is it wouldn't rest

  • How do share a very large file?

    How do share a very large file?

  • Reset issue, message F5 579

    Hello All, while try to reset a document I receive the error message  "Resetting this reverse document is not possible". In the long text of the message it says The system required a reverse document to be created after resetting a clearing procedure

  • Office 365 account 60 minutes

    I have an Office 365 home account, installed Oct. 2014 and am located in the UK. There are 3 users on the account (out of max. 5). One other user is using the monthly 60 minutes Skype credit. I am looking for it on my own account and it doesn't show.

  • MS Access XML export

    Hi, This is not really a Spry issue, but it is something that many of us may encounter. I use MS Access to generate an XML file from a table. In that table I have several date fields, not matter how I format them, (e.g. mm/dd/yyyy) when I export to X