String cmd = "cmd.exe /c start ";
String file = "c:\\";
Runtime.getRuntime().exec(cmd + file);
In this quick tip, I’m going to show you how to pop open Windows Explorer directly from your Java application. The snippet above constructs a command that tells cmd.exe to run the built‑in start utility. When start receives a folder path, Windows opens Explorer instead of a console window—exactly what we want.
How it works step by step:
- The
cmd.exe /cprefix runs a command and then terminates the command prompt. startlaunches a new process in a separate window; for directories, this means Explorer.Runtime.getRuntime().exec(…)hands the assembled string to the operating system.
One thing to keep in mind: if the directory path contains spaces, you must wrap it in escaped quotes. For example:
String file = "\"C:\\Program Files\"";
Runtime.getRuntime().exec("cmd.exe /c start " + file);
Alternatives: Starting with Java 6 you can use the Desktop API:
Desktop.getDesktop().open(new File("C:\\"));
That approach is more portable, but it may fail on headless systems or if the file isn’t a directory. For Windows‑specific utilities the start trick is reliable and gives you full control.
If you need to capture output or handle errors more gracefully, switch to ProcessBuilder. As an example:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "start", "C:\\");
pb.start();
Testing…