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.

Similar Messages

  • How to clear the DOS screen through java program

    how to clear the DOS screen through java program

    Just some Friday fun. Use the telnet program that comes with Windows and supports VT escape sequences.
    import java.io.*;
    import java.net.*;
    public class AutoTelnet {
         private static Socket s;
         public static void main(String[] args) throws Exception {
              Thread t = new Thread() {
                   @Override public void run() {
                        try {
                             s = new ServerSocket(5555).accept();
                        } catch (IOException ex) {
                             ex.printStackTrace();
              t.start();
              Process p = new ProcessBuilder("cmd", "/C", "start", "telnet", "127.0.0.1", "5555").redirectErrorStream(true).start();
              t.join();
              PrintStream ps = new PrintStream(s.getOutputStream());
              ps.println("Screen will be cleared in 5 seconds");
              ps.println("5");
              Thread.sleep(1000);
              ps.println("4");
              Thread.sleep(1000);
              ps.println("3");
              Thread.sleep(1000);
              ps.println("2");
              Thread.sleep(1000);
              ps.println("1");
              Thread.sleep(1000);
              ps.println("\u001b[2J");
              Thread.sleep(5000);
    }

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

  • 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 a DOS command in java

    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,
    Bernard

    First, 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

  • 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 create an Oracle DATABASE through Java Programming Language.. ?

    How to create an Oracle DATABASE through Java Programming Language.. ?

    Oracle database administrators tend to be control freaks, especially in financial institutions where security is paramount.
    In general, they will supply you with a database, but require you to supply all the DDL scripts to create tables, indexes, views etc.
    So a certain amount of manual installation will always be required.
    Typically you would supply the SQL scripts, and a detailled installation document too.
    regards,
    Owen

  • How to execute dir dos command in Runtime Execution

    Hi All,
    Does anybody know how to execute the dir command in DOS in the runtime execution
    for example,
    when we open the command prompt,
    c:\Documents and Settings\java> e:
    e:\cd java
    e:\dir *.*
    how we can list the directory in runtime execution?

    Process childProcess = Runtime.getRuntime().exec("cmd /C dir *.*");or try with
    ProcessBuilder pb = new ProcessBuilder("cmd /C dir *.*");
    Process childProcess = pb.start();
    NOTE: We can use the ProcessBuilder class from J2SE 5.0+.
    for further reference check the below link
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=3
    and don't forget to go through API documentation for java.lang package
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/package-summary.html
    and if you want to implement it through Java which provides you a list of Files & directories in the present directory here is an example of such code snippet REF:as insisted by my fellow poster.
    File file = new File("<present_directory_path>");
    if(file.isDirectory()){
       String fileNames[] = file.list();
            for(String fileName:fileNames)
               System.out.println(fileName);
      fileNames = null;
            or for detailed info use
             File files[] = file.listFiles();
             for(File fileEntity:files)
                System.out.println("FILENAME:"+fileEntity.getName+",IS FOLDER:"+fileEntity.isFolder()+",ABSOLUTE PATH:"+fileEntity.toString()+"FILE SIZE:"+fileEntity.length());
             files = null;
    }and please do not forget to go through File API Documentation provided as recommended by my fellow poster.
    hope this might help :)
    REGARDS,
    RaHuL

  • 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 shell command in java?

    here, my environment is redhat 7, jdk 1.5.
    i don't know how to use the shell command in java.
    i want to use this function:
    #include <stdlib.h>
    int system(const char * string);
    please give me some ideas. and Thank you so much if coming with a little demo.

    i know i should use JNI. because i have to use C lib.
    but i have already use JNI to wrapper the original code the cpp code and java code is :
    //: appendixb:UseObjImpl.cpp
    //# Tested with VC++ & BC++. Include path must
    //# be adjusted to find the JNI headers. See
    //# the makefile for this chapter (in the
    //# downloadable source code) for an example.
    #include <jni.h>
    #include <stdlib.h>
    extern "C" JNIEXPORT void JNICALL
    Java_UseObjects_changeObject(
    JNIEnv* env, jobject, jobject obj) {
    jclass cls = env->GetObjectClass(obj);
    jfieldID fid = env->GetFieldID(
    cls, "aValue", "I");
    jmethodID mid = env->GetMethodID(
    cls, "divByTwo", "()V");
    int value = env->GetIntField(obj, fid);
    printf("Native: %d\n", value);
    env->SetIntField(obj, fid, 6);
    env->CallVoidMethod(obj, mid);
    value = env->GetIntField(obj, fid);
    system("preprocess -path sha.c");
    printf("Native: %d\n", value);
    } ///:~
    //: appendixb:UseObjects.java
    // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
    // www.BruceEckel.com. See copyright notice in CopyRight.txt.
    class MyJavaClass {
    public int aValue;
    public void divByTwo() { aValue /= 2; }
    public class UseObjects {
    private native void
    changeObject(MyJavaClass obj);
    static {
    // System.loadLibrary("UseObjImpl");
    // Linux hack, if you can't get your library
    // path set in your environment:
    System.load(
    "/root/jproj/UseObjImpl.so");
    public static void main(String[] args) {
    UseObjects app = new UseObjects();
    MyJavaClass anObj = new MyJavaClass();
    anObj.aValue = 2;
    app.changeObject(anObj);
    System.out.println("Java: " + anObj.aValue);
    } ///:~
    i modify this two file which is from TIJ-2edition.
    the output is
    Native: 2
    Native: 3
    Java: 3
    but what i want to be executed "preprocess -path sha.c" does not work.
    i have change the command to, such as "df", "ls" etc. but none of them works
    please help me.

  • 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

  • Please help How can i run Os commands thru Java programs

    Hey,
    I want to stop and restart the linux server thru java program.Is it possible to run the os commands thru java program.
    I had it thru Runtime.getRuntime().exec("*.exe");
    it only runs the exe files.How can run files other than exe files like .bat,com ans shell commands..Any body knows please help with the code..or mail to this address
    [email protected]
    thankyou,
    regards,
    j.mouli

    What about "start command.com /C execute.bat", or using the overload that takes a String[] as argument?
    What if you use the the full path of execute.bat?
    What error code do you get?
    And what comes th linux, I'm not sure... you'll need a shell interpreter there too, me thinks. (never had to run anything with runtime.exec on linux). Check the man pages if csh, bash, ksh, or what ever shell you like.

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

  • Executing a dos command from java in windows nt

    i need to execute the
    " net send"
    command from the command line in windows nt, from within my java program... is there any way that i can execute cmommands in the dos command shell? or rather, does anybody know a way i can send a message ( in windows ) from java, from one computer to another over the lan?? I cannot have a java programming running on all the other computers, so i cannot make my program serve, it must just send the messges using a lan command....
    (the net send command just sends a message in the form of a pop up box on the receiver's screeen)
    thanks a bunch guys!!!
    Thanks a bunch guys!!!!

    you can do that with exec() in Runtime.
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(command here);but before you do that you need to read this:
    http://www.javaworld.com/jw-12-2000/jw-1229-traps.html
    hth
    partha

Maybe you are looking for