Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mkdir and rmdir commands in a java program

I want to use system commands like mkdir and rmdir while running a java program.

How can I do that?

like image 219
Andersson Melo Avatar asked Apr 22 '10 19:04

Andersson Melo


3 Answers

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

http://www.exampledepot.com/egs/java.io/deletefile.html
http://www.roseindia.net/java/beginners/java-create-directory.shtml

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.

like image 178
Chris Dennett Avatar answered Nov 01 '22 18:11

Chris Dennett


As the other mentioned, you shouldn't do this for simple file management. But to have it mentioned: The Java API has a class called Runtime, that allows system calls... for example:

Runtime.getRuntime().exec("some_command");
like image 4
cyphorious Avatar answered Nov 01 '22 18:11

cyphorious


The best is not to, but rather find the pure Java API function that does it. It is cleaner, easier to understand and much less error prone. It is also the only way to do Java that is write once run everywhere. Once you are calling shell commands, you are tied to that shell.

In your case you are looking for the java.io.File class, and specifically the mkdir and delete methods.

like image 3
Yishai Avatar answered Nov 01 '22 18:11

Yishai