Thursday, May 19, 2011

How to execute a DOS command using Java.

As you know "mkdir" is the DOS command which lets you create a new folder at a given location.
In order to create a folder named as "MyFolder" in your "C:" drive you can use the following command.
>>mkdir c:\MyFolder

But in java you need to do an additional work to execute this command.
So you have to add "cmd /c" to your command.
Following code creates a new folder named as "MyFolder" in drive "C:".
String cmd = "cmd /c";
String command = "mkdir";
String folderName = "C:\\MyFolder";
Runtime.getRuntime().exec(cmd + " " + command + " " + folderName);

But what will happen if your folder name contains space characters.
For an example if the name of your folder was "My Folder" instead of "MyFolder".
Then you should add extra double quotes and escape them as below.
String folderName = "C:\\\"MyFolder\"";

No comments:

Post a Comment