Andersson Melo Andersson Melo - 1 year ago 171
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download