1

I am finding an issue while deleting a folder from Java. I used following commands without luck. However, I am able to delete folder through command prompt using Windows 8.1:

String command1="rd /s /q"+Path;
String command2="rmdir /s /q \""+Path+ "\"";
String command3="del /q \""+Path+ "/*\"";

The exception I get in all the three cases is:

java.io.IOException: Cannot run program "rmdir": CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) at java.lang.Runtime.exec(Runtime.java:620) at java.lang.Runtime.exec(Runtime.java:450) at java.lang.Runtime.exec(Runtime.java:388)

Using Code:

try {
    Process process = Runtime.getRuntime().exec(command);
} catch (Exception e) {
    e.printStackTrace();
}

P.S.: Its a locked file

Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34
FX_Programmer
  • 115
  • 2
  • 11
  • 1
    Possible duplicate of [How to delete a folder with files using Java](https://stackoverflow.com/questions/20281835/how-to-delete-a-folder-with-files-using-java) – Jose Da Silva Gomes Mar 27 '18 at 16:42
  • You shouldn' use commands for that, java already provides that funtionality (in a multiplatform way). – Jose Da Silva Gomes Mar 27 '18 at 16:43
  • That doesn't serves my purpose I tried many thing but it does not delete a locked file! – FX_Programmer Mar 27 '18 at 16:44
  • In you question you didn't even mention that you were trying to delete a locked file – Jose Da Silva Gomes Mar 27 '18 at 16:47
  • but the exception does not care about whether the file is locked or not. It says "The system cannot find the file specified" – FX_Programmer Mar 27 '18 at 16:49
  • 1
    The real issue is that `del`, `rd` and `rmdir` are shell commands implemented within `cmd.exe` and do not have executable counterparts in Windows. They will also fail if the file is locked, although it's not exactly clear what you mean by "locked". – Jim Garrison Mar 27 '18 at 17:29

1 Answers1

0

You can use: "cmd /c rmdir /Q /S".

The system tries to run rmdir.exe and then you get this failure.

  • It's not portable. Better to stick to java functionality for deleting folders. – Sarah Phillips May 20 '22 at 18:53
  • @Sarah Phillips what do mean by portable? you mean it's OS dependent? I think that it's better to do it with java too, but that is not what the question is about. He didn't ask what is the best way. He asked why this specific code is failing and I had an answer to it. – Hodiya Eyal May 21 '22 at 13:36