Andersson Melo Andersson Melo - 1 month ago 24
Java Question

How to use mkdir and rmdir commands in a java program

I want to use system commands like

while running a java program.

How can I do that?


Why do you want to use the command line? FYI, there are built-in platform-independent File classes.

Make directory:

new File("dir path").mkdir();

Remove directory:

new File("dir path").delete(); 

'new File' here is a bit of a misnomer, it isn't actually creating the directory or a file. It's creating a Java resource hook which you can use to query or operate upon an existing filesystem resource, or create a new one at your request. Otherwise, use Runtime.getRuntime().exec("command line here") for using command line operations (not advised!!).

Edit: sorted out the problem the question poster was having:

String envp[] = new String[1];
envp[0] = "PATH=" + System.getProperty("java.library.path");
Runtime.getRuntime().exec("command line here", envp);

Note the insertion of envp into the exec(..) method call, which is basically the PATH variable from the environment.