Search code examples
javaruntimetemp

Deleting temporary file using Java runtime.exec function


I'm stuck in a situation.

String tmpfolder = System.getProperty("java.io.tmpdir");
\\this is the path C:\Users\biraj\AppData\Local\Temp\ 
tmpfolder = tmpfolder.replace("\\", "\\\\"); 
Runtime.getRuntime().exec("cmd /c del "+tmpfolder+"IEDriver.dll /f /s /q"); 

When I run this code it does not delete the IEDriver.dll file. But when I give the static path of the temporary folder then it deletes that file:

Runtime.getRuntime().exec("cmd /c del C:\\Users\\biraj\\AppData\\Local\\Temp\\IEDriver.dll /f /s /q"); 

Can anyone explain to me why the first code didn't work? What's wrong in that?


Solution

  • The problem is that you are changing literal \ into a literal \\ in your second line. When we write code, we use \\ inside a string to represent a literal \ to the program, but your tmpfolder variable already has the correct literal \ inside it.

    If you delete the following line, it should work.

    tmpfolder = tmpfolder.replace("\\", "\\\\"); 
    

    The easiest way to understand the difference is to just print the string you constructed, as well as the literal string and compare them visually.

    System.out.println("cmd /c del "+tmpfolder+"IEDriver.dll /f /s /q");
    System.out.println("cmd /c del C:\\Users\\biraj\\AppData\\Local\\Temp\\IEDriver.dll /f /s /q")
    

    Another possible problem is that you need to change

    "IEDriver.dll /f /s /q" 
    

    to

     "\\IEDriver.dll /f /s /q"
    

    Of course the visual comparison will answer this question definitively.