How to make a system call using Java. When I try something like the following, it gives me an IOException with an error code 2: RunTime rt = RunTime.getRunTime() rt.exec("dir"); I know one solution to this is to put the "dir" command into a .bat file, and then pass the .bat file name as an argument to exec(). But is there any solution that does not need to make use of a .bat file?
It's an interesting question... I run Windows 2000 Pro, with J2SE SDK 1.4.1 installed. I tried your code, and faced the same problem. I then tried to run a process that I knew didn't exist ("blah") actually. This also reported error 2, which made me think that it wasn't seeing the "dir" command. So, I tried to execute the Windows Explorer application by typing rt.exec("explorer"). Surprise, surprise, it works... Take another experiment, and try to run "dir" from your Start > Run command: Windows reports a spectacular: "Cannot find file". I would guess that because all of the latest Windows editions (NT and 2000 onwards) don't rely on MS-DOS as previous editions did, then there is no solid command-line, instead it is run as a separate program (called "system32\cmd.exe") for the convenience of users and administrators. Because Java runs on Windows, and not DOS, it is not capable of running commands that Windows can't, so shellcommands (i.e. commands built in specially to the command-line program) will not run. However, you can run executables, including explorer, your web-browser and the java compilers and JRE. Windows recognises that a batch file is a DOS command-line formatted file, so it opens it for you in the cmd.exe program and runs it. So this may be the way to proceed. If you need a test to see which commands work by default in Windows, try the Start > Run utility... Sorry I can't be of more help!
Charles Lyons (SCJP 1.4, April 2003; SCJP 5, Dec 2006; SCWCD 1.4b, April 2004)
Author of OCEJWCD Study Companion for Oracle Exam 1Z0-899 (ISBN 0955160340 / AmazonAmazon UK )
I've found a possible solution which outputs the directory [or dirs.] supplied, given the "dir" command; take a look at the code snippet below, it uses the cmd.exe executable, with the "/c" switch to execute a command (here "dir /s"):
This will output all directories and subdirectories (note the "/s" switch after "dir") to the Java console. This would appear to answer your original query and solve the problem... However, it is NOT platform-independant, and will not necessarily work on other versions of Windows.