1

So I want to use the windows tree's command to display the a hierarchy graphical representation of all the files present in a directory.

But when I run the command,

Process cmd=Runtime.getRuntime().exec("tree \"path\" /f /a");

I get this error,

java.io.IOException: Cannot run program "tree": CreateProcess error=2, The system cannot find the file specified

Does java.lang.Runtime.exec(String command) only work for certain commands?

pha1don
  • 33
  • 1
  • 4

1 Answers1

3

The program you're trying to execute is called tree.com.

It is the command-line interpreter cmd.exe that uses the PATHEXT environment variable to search the path for programs with various extensions. Java's API doesn't.

So you have 2 choices:

  • Add the extension:

    Process cmd = Runtime.getRuntime().exec("tree.com \"path\" /f /a");
    
  • Run it using cmd.exe:

    Process cmd = Runtime.getRuntime().exec("cmd.exe /c tree \"path\" /f /a");
    

The .exe extension is optional, e.g. "cmd /c tree \"path\" /f /a" works too, but any other extension (e.g. .com) is required, and scripts (.bat, .cmd) must be run with cmd.exe.

Andreas
  • 154,647
  • 11
  • 152
  • 247