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

Similar Messages

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

  • 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

  • Use several DOS command from java program

    Using "Runtime.getRuntime().exec(toto.bat)" I have no problem to run a Command in my DOS window...
    But the problem appear when I want to call another command in this same window from myApp.java...
    In fact after executing the first command I find no way to have another access to this DOS window...
    Is there any way to set the Process created by calling exec() method as the default system??
    Hope my explications are clear...
    Does someone have the solutions...this will help me so much...
    bilbou.

    ok but I have found no forum which resolve my problem...can you give more details about what you think concerning the solution of my pb...
    bilbou.

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

  • Executing a dos command from java

    Hi guys.
    This line works fine:
    process = Runtime.getRuntime().exec("command.com /C c:\\test.bat");
    But this line do nothing:
    process = Runtime.getRuntime().exec("command.com /C c:\\test\\test.bat");
    I need to run a dos file in some directory in my HD. It works fine in root, but do nothing when I change to directory. I do this from an applet.
    Any ideas/suggestions?

    Any ideas/suggestions?The file isn't actually there (it isn't in the directory.)
    There is a permisions problem (which is unusual but not impossible on windows.)
    The script itself is failing - you didn't indicate "how" it doesn't work so this is possible.

  • DOS command from java applet

    Hi, I need to perform a DOS command from Java (using WFC if needed)...
    I have no idea, so please help!
    Thank you.

    OH OH OH WAIT! It is an Applet! i think there will be some security issues here! Sure enough you can't execute commands on the system from an applet unless you make some changes on the java.policy files on the client machine (that means, if your applet is in a web page, every machine which view your page).

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

  • 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

  • Dos command from java

    hi all
    how do i run dos commands from java??????????

    Using Runtime#exec().
    Also see http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html

  • 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

  • Can I execute MySql's command from java application?

    Can I execute MySql's command from java application? And how?
    For example :
    load data local infile 'D:\\myData.txt'
    into table myTable
    fields terminated by ';'
    lines terminated by '\n';

    1. get the jdbc driver for mysql from the mysql site at: http://dev.mysql.com/downloads/connector/j/5.0.html
    2. follow the installation instructiions... which you'll also find in your mysql manual...
    Happy travels. Keith.

  • Executing a DOS Command from JSP

    How do i execute a Dos command from within JSP. I would like to execute a sql Loader command .
    Thanks

    You use Runtime.execute().
    Take a look here for a few of the tricks involved in it:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

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

  • Error using DOS Command from Java

    Hi,
    I am using the following code to execute the DOS command to delete a file from Java.
    cmd = "del " + fileName;
    Runtime run = Runtime.getRuntime();
    Process proc = run.exec(cmd);
    Getting the following exception during runt time.
    Exception = java.io.IOException: CreateProcess: del D:\LAWDOCS\P50074\12\3\36857.3  error=2 --
    Can some body throw light on this?.
    Thanks,
    Jeyaraman R

    "del" is not an actual executable file, but instead a command in the command interpreter. So you can't just execute del like that, you have to run the command interpreter and tell it to execute the del command.
    If you are on windows NT, 2000 or XP, replace your command with "cmd /C del " + filename.
    If you are on Windows 95, 98 or ME, use "command /C del " + filename. (I am not quite sure if the switch for this is called /C on old windows version.)
    (But why not use File.delete()?)

Maybe you are looking for

  • ICloud with os lion 10.5.8 and IPhone 3Gs

    What a pain in the A**.  Is there anyone out there that can assist me? I would soooooo appreciate the feedback.  Not sure if its fully functional with this combination. (ICloud, Lion 10.5.8, IPhone 3Gs)  I dont want MobileMe.  I have an Mac email. I

  • Macbook to macbook pro

    if i take my computer to the mac store and give my computer and the money, would you change it ?

  • Poll interval with sender comunication channel in many servers

    Hello everybody , I have a question, we have PI 7.1 and we have the next requirement: File Adapter Sender->PI->SAP ECC now the file need to be picked up from 20 different servers, the file is in the same format in all the servers, is there a way in P

  • Styling font

    Hello amigos/amigas. I am trying to style some font I'm importing from a simple .txt file. I know how to set the font family, size, etc. however, I want to change the style of the font as well as the family. The font I am defining is "frutiger", but

  • I have some problems with work in Flash cs6

    I have some problem with my game when I created it using adobe flash cs6 When the duck hits the screen, like from right to left it shows TypeError: Error #1009: Cannot access a property or method of a null object reference.   at Duck/ducksmove()   at