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\"");

Similar Messages

  • How to run dos command on java

    would java run the dos command ?
    if yes ~would you mind give me some example~please~

    ..or just use:
    Runtime.getRuntime().exec("cmd /c commandyouwanttouse");
    Hope it works!                                                                                                                                                                                               

  • Running DOS command from JAVA

    Hi ,
    I would appreciate if anyone could tell me how to run DOS command such as "del" using JAVA language .Thank you.

    <steps onto soapbox>
    Surely for something like 'del' we should be advocating a non-OS specific method so we don't lose sight of Java's cross platform abilities.
    If it has to run an OS specific thing fine, but please look for a non OS specific solution first.
    <steps off soapbox>

  • 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

  • Run dos command from java

    May I ask how I should write if I want to execute a dos command in java? The command is :
    "C:\Program Files\Real\realproducer\rmeditor -i abc.rm -d abc.txt". Should I use array?
    Thanks!

    why an array ?
    String command = "C:\\Program Files\\Real\\realproducer\\rmeditor -i abc.rm -d abc.txt";
    Process p = Runtime.getRuntime().exec( command );what about the seach function on the left side ? ;-)
    tobias

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

  • HOW DO I RUN DOS COMMANDS ON JAVA

    I SWEAR, I'LL PAY YA IF YOU HELP ME!!!
    Hi, this is the thing:
    have you ever run the "time" command on a DOS console?? if you have, you know that it shows the current time, and lets you set a new time.
    well, i need to make a java program to open a DOS console and execute the command, and making it able to write in information on the console so it sets a new time.
    MY PURPOSE IS NOT JUST WATCHING THE CURRENT TIME!! so please don't tell me to use System.getCurrentTimeMillis() or something like that; i explicitly need to run that DOS command. what's the Java code to do it??
    thank you!! and please attach your account # so you get a $50 deposit by the end of the week
    thank you!!

    Thanks a lot, you all guys, but i don't know what's with this thing.... it always throws an IOException, with the following exception stack trace:
    java.io.IOException: CreateProcess: temp.bat error=0
            at java.lang.Win32Process.create(Native Method)
            at java.lang.Win32Process.<init>(Win32Process.java:63)
            at java.lang.Runtime.execInternal(Native Method)
            at java.lang.Runtime.exec(Runtime.java:550)
            at java.lang.Runtime.exec(Runtime.java:416)
            at java.lang.Runtime.exec(Runtime.java:358)
            at java.lang.Runtime.exec(Runtime.java:322)
            at Tarea.main(Tarea.java:15)and it will come out the same shit over and over. The above case was thrown by the line Runtime.getRuntime().exec("temp.bat") where temp.bat is a file where the only thing written in it is the word "time". and you can change the string parameter of the method exec, and thats what will change in the stack trace above.
    I also tried "cmd", "command", and "command.com". With the last one, it opens the command.com application but it freezes and does nothing. With the other two, appears the same old shit from above.
    Please help me!!
    Thank you...

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

  • Running Dos Command using Java

    How do i run a particular Dos command using a simple java class?

    Process process = Runtime.getRuntime().exec( ... );
    Search the forum. There are plenty of examples.

  • How do run unix command in java

    hi
    All unix command working fine in our java program.
    but i want change user in linux by using java. it's not working.
    "su root" This command onely not working.
    anybody know help me
    This is my ID [email protected]
    This my code
    <% String s = null;
    try{
    Process p = Runtime.getRuntime().exec("su root");
    BufferedReader stdInput = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new
    InputStreamReader(p.getErrorStream()));
    out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null)
    out.println(s);
    catch(Exception e) {}
    %>

    I don't have further info to add to your first post, but think your guess seems quite reasonable. I thought of starting a new thread on the same topic, but think this (question) fits in here, too.
    I have Java code (freeware, not opensoure), intended for Unix, which basically provides the graphical interface and relies on an I/O layer (C + shell scripts) to do most of the work. I have access to the C+shell scripts which are opensource. I ported it to Cygwin and want to use it under Windows (there is no Cygwin native Java VM).
    My problem now boils down to " how to run commands under Unix and what differences are there with Windows". What are the variants?
    I have to guess what the program is doing when I get an IOException at some point. E.g.: a call to shell script may be made in a different way as to a compiled exe in Unix?. I found a way to bypass path problems because forward slashes are also accepted and /cygdrive/c construct can be replace by c:/; shell scripts can be compiled into exes using shc and they work; if symbolic links are replaced by duplication of exe files, they work. What will happen in an instance whereby a process runs a shell script dynamically, through a pipe (the shell script is compiled in the Cygwin/win version and receives parameters) in a construct like:
    pipefp = epopen(cmdbuf,"w"); /* (cmbuf is "makehdr par1 par2 ... ") (makehdr was a shell script and is now compiled exe for Cygwin/Windows) */?.
    Thanks.
    LT

  • Error while running DOS command in Java

    Hi all,
    I use "runtime" class to execute a DOS command "copy C:\\pathname\\*.* C:\\backupPathname\\". But I saw an error msg "CreateProcess: copy C:\pathname\*.* C:\backupPathname\ error=2".
    I did create a folder C:\backupPathname\ before running the DOS command.
    Pls help me all Java genius.

    I ended up writing a small 'c' program and pasing the command in to it from java. The problem seems to be that in dos, unlike unix, the copy command is not a program, rather the command is interpreted by the command.com program.

  • Running Dos command in Java

    hey, Just wondering can anyone help me get started, i pretty new to java and wanted to run the date command in Dos from a java application. If i could just know where to begin or even if this is possible, it would be much appreciated!!

    If you're using Runtime.exec() you need to read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    If you're new to java it might be a bit heavy, but definitely add it to your "Favourites" for later!

  • How to run system commands from JAVA

    Hi Friends,
    How to run windows system commands from JAVA
    Runtime r=Runtime.getRuntime();
    r.exec("dir");
    Throwing following Exception
    CreateProcess :dir error=2
    Thanks in advance
    Hamsa

    Hi ,
    in Windows NT this is not possible, you can use the following :
    Runtime r=Runtime.getRuntime();
    StringBuffer sbuf = new StringBuffer();
    String dir = new String();
    java.lang.Process proc = r.exec("cmd /c dir");
    InputStream is = proc.getInputStream();
    int ch ;
    while((ch=is.read() ) != -1)
    sbuf.append((char)ch);
    is.close();
    dir = sbuf.toString();
    System.out.println(dir );

  • How to run dos command in jsp

    hi all,
    i am running this command at command prompt
    like below
    java filename argument.
    ex: java validateuser user1
    it works fine at command prompt. and the same command i want to run in jsp
    so i tried like this
    Runtime x = Runtime.getRuntime().exec("java validateuser user1");
    whats happenning here is it just opening command promot of java.exe but its not running validateuser.
    any help will be greatly appreciated.
    advance thanks.

    why on earth are you trying to run java.exe on the command line through JSP?i think you misunderstand my question.
    i am not trying to run java.exe on through jsp.
    I am trying to run a validateuser user1 in jsp .
    Note:validateuser is a java file which take one argument.here in my scnerio user1 is the argument.

  • How to run solaris commands through java code ....

    Hi,
    actually i want to run some solaris commands for zipping some files on Solaris OS...
    any idea how can i do that ?
    thanks

    public class TABLES
    public static void main( String[] args )
                      //database is connected
            try
                   Connection con = null;
                   Statement stmt = null;
                   String strShowTables = "";
                ResultSet resultSet = null;
                   // CBA Statistics period is m_lStatisticsPeriod minutes
                   con = DriverManager.getConnection( g_strRWURI, g_strRWUsername, g_strRWPassword );
                   stmt = con.createStatement();
               ResultSet rs = stmt.executeQuery("use db");
             resultSet = stmt.executeQuery(strShowTables);
        String tableName = "";
             while(resultSet.next()){
    tableName = resultSet.getString(1);
              System.out.println(tableName);
            break;
    String strCmd = "tar cvzf file.tar.gz var/lib/mysql/db/GROUPS.*";
    Process p= Runtime.getRuntime().exec(strCmd);
    System.out.println(strCmd);
        stmt.close();
                rs.close();
                resultSet.close();
                   con.close();
              catch ( Exception e )
                   System.out.println( ": Failed to create database connection (" + e.getMessage() + ")" );
                   e.printStackTrace();
              catch ( Throwable t )
                   System.out.println( " Throwable: " + t.getMessage() );
                   t.printStackTrace();
        }//end of main mehtod
    }//END OF CLASSi hava tried the above code... what the problem is
    when is run that command on shell >    tar cvzf file.tar.gz var/lib/mysql/db/GROUPS.*i works fine but in code even though it didn't give any error but the created "file.tar.gz" is empty...
    Edited by: aftab_ali on Apr 7, 2009 7:15 AM
    Edited by: aftab_ali on Apr 7, 2009 7:17 AM

Maybe you are looking for

  • Need to get mass info from my XML library file

    Hi. A while ago I was trying to set up my computer so that a user other than me could play my iTunes songs but not be able to delete them. In the course of that I somehow moved a file I shouldn't have and iTunes lost all my info. I finally managed to

  • GR value is greater than PO value.

    Hi friends, I got a strange situation. I created a PO material 'x' for the quantity 900 with price of USD 162.00/ea. Total amount is USD 145800. But when I do GR it posted to amount USD 265,356.00. quatity is same as 900. Tha material is valuated wit

  • Dynamic structure to create

    Hi, I have text which is created on SO10. I have declaration part on this element. LOOP AT lt_tline INTO ls_tline. ELSEIF ls_tline-tdline CS text-009. "text-009 contains 'Declaration'           PERFORM f_offset_text USING ls_tline-tdline             

  • I cannot load certain pages using FireFox i could days ago. Pages load fine IE.

    I use google doc to link me to pages/spreadsheets for work, and i was accessing everything fine till 5 days ago. Now i am being redirected. I get a glimpse of the page/spreadsheet then it begins to redirect me with a blank screen. Disabled Java Add o

  • Break point in SAP Script

    Hi Guys, I just wanted to clarify something. In report if i do write break point then while running the program the system will halt there allowing me to debug. Is this functionality possible in SAP script too?? I mean is breakpoint a valid statement