0

I'm trying to Delete the directory by java code, Now use case is : if file is already opened then it should close it first , and then i can directly delete the directory .

I was trying to close the file using FileoutputStream but I'm not able to make object of FileoutputStream it is showing error like "The process cannot access the file because it is being used by another process"

is there another method which will help me out ?

Ram
  • 233
  • 1
  • 17
  • add your code snippet, – Manikanta Reddy Feb 01 '17 at 05:24
  • No - if another process has a file open (on Windows, which is your platform given your error message as Linux doesn't care that another process has a file open) then you cannot do anything about that from Java. You need to use Windows-specific tools to determine which process has it open and to close that process automatically if you want that. – Erwin Bolwidt Feb 01 '17 at 05:27
  • This approach will not work. You are trying to open a new file handle and you will be able to close that only. The existing file handle still remains open. – Himanshu Bhardwaj Feb 01 '17 at 05:27
  • Is the file opened by your own Java application that is trying to close the file? – DevilsHnd - 退職した Feb 01 '17 at 05:29
  • @DevilsHnd No. File is opened manually and that need to close for parent folder deletion through my java code – Ram Feb 03 '17 at 05:48

1 Answers1

2

If the file you want to delete has been opened by your Java Application with perhaps the use of the Runtime.getRuntime().exec() method or by any other means then that file must be closed before you can carry out the task. And of course, because the file is open you can not delete the home folder (directory) of that file either, the file will need to be closed first. This is a OS safeguard which makes total sense, why would we want to delete something that is in use by something else?

In order to close the file you will need to know the name of the process which is using it, for example if a Text file named MyText.txt has been opened with MS Windows NotePad.exe then you must close the NotePad.exe process that is holding the file MyText.txt open.

Below I provide a simple method which can close an open external process for you providing you supply the proper Process Name. From our example above this would be "Notepad.exe"

public static void killProcess(String processName) {
    // PLEASE NOTE: This method will currently Kill "ALL" 
    //              open processes of the supplied process 
    //              name unless commented code changes are 
    //              made.
    try {
        Runtime rt = Runtime.getRuntime();
        // For Windows OS...
        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            rt.exec("taskkill /T /F /IM " + processName);
            //rt.exec("taskkill /T /F /PID " + Long.parseLong(processName)); // Supply the PID value as string
            //rt.exec("taskkill /F /FI \"WINDOWTITLE eq " + processName + "\" /T"); // Supply the window title bar text.
            // If you want to kill only a single instance of the 
            // named process then get its PID value and use:
            // "taskkill /T /F /PID PID_Value"  OR you can provide
            // the window title and use:
            // "taskkill /F /FI \"WINDOWTITLE eq " + processName + "\" /T"
        }
        // For OSX And Linux OS's...
        else {
            rt.exec("sudo killall -9 '" + processName + "'");
            //rt.exec("kill -9 " + Long.parseLong(processName)); // Supply the PID value as string
            // If you want to kill only a single instance of the 
            // named process then get its PID value and use:
            // "kill -9 PID_Value"
        }
        rt.freeMemory();
    } 
    catch (IOException | SecurityException | IllegalArgumentException ex) {
        ex.printStackTrace();
    }
}

As the comments state at the beginning of this method code, ALL currently running processes of the supplied process name will be terminated. If you only want to terminate a specific instance of a process, as with our example above for instance, and you have four other instances of Notepad.exe open editing other text files, then you would need to change the method code to be this:

rt.exec("taskkill /F /FI \"WINDOWTITLE eq " + processName + "\" /T");

instead of this:

rt.exec("taskkill /T /F /IM " + processName);

and of course you would call this method something like this:

killProcess("MyText.txt - Notepad");

where you supply what is in the window title bar of the application. Once the above method has completed you can then delete the MyText.txt file and the folder it resides in since it is no longer being used.

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
  • Actually the use case is I am creating one folder structure , in which i am trying to create a excel files. For the second time when user tries to run the code again , then previous folder must get deleted . But If some of the excels are already opened by the user ,then we are not able to delete existing directory, I we can not close the file thro' the code it self . we should give a warning to user for closing the file first. And Let the user do the closing work first. Is it a only solution or is there anything else? – Ram Feb 05 '17 at 05:26
  • I see...In your particular case then you definitely want the Users to close their respective files first (to be polite). The only thing I can think of in that case then is to create an additional thread with a timer to continuously try to delete the folder(s) and purposely catching and ignoring the Exception. When success does happen you can have a Message Box display that to you on your screen after the timer is stopped and the thread is terminated. – DevilsHnd - 退職した Feb 06 '17 at 02:09
  • Yes. Thank u so much :) – Ram Feb 06 '17 at 04:44