How do I execute
rd /s /q c:\folder
in Java?
It woks perfectly on the command-line.
How do I execute
rd /s /q c:\folder
in Java?
It woks perfectly on the command-line.
Check the Runtime.exec method, which lets you call external processes. (Bear in mind that you lose some platform independence as this would rely on the machine having the rd
command installed and on the path.)
A better option might be to do the same thing in pure Java - the following should be equivalent:
private void deleteDirectory(File directory)
{
for (File entity : directory.listFiles())
{
if (entity.isDirectory())
{
deleteDirectory(entity);
}
else
{
entity.delete();
}
}
directory.delete();
}
deleteDirectory(new File("C:\\folder"));
Adding error-checking as required. :-)
Look at File.delete(String path)
method, i.e.:
new File("c:\\folder").delete();
If the /s
(recursive) deletion is important, then (untested):
public void deltree(File file) {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
deltree(f);
}
}
file.delete();
}
public void deltree(String path) {
deltree(new File(path));
}
invoked as:
deltree("c:\\folder");
You only can delet empty directories in Java. First you have to delete the files and sub directories.
public static boolean removeDirectoryRecursively(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = removeDirectoryRecursively(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
Check out FileUtils in Apache Commons-IO; in particular, the deleteDirectory and deleteQuietly methods, which can both recursively delete a directory.
If you want to execute it exactly the way you specified, you can do
Process p=Runtime.getRuntime().exec("cmd.exe /k rd /s /q c:\\folder");
According to dtsazza's answer:
Runtime.getRuntime().exec("cmd.exe /k rd /s /q c:\\folder");
It works perfectly under WinXP SP3. The /k
parameter shows, that a command will follow that has to be executed out of the cmd.exe
.
Good luck with that!