Thursday, August 20, 2009

Delete a file only when it is closed

Hi, below is the code which will create and open a file using window resources and if the file is already created then it will open the file.

try {
Process pc = Runtime.getRuntime().exec("C:/WINDOWS/ServicePackFiles/i386/notepad.exe C:/CheckDemo.txt");
} catch (IOException ex) {
ex.printStackTrace();
}

However I was wondering, if we need to open the file in temporary mode; meaning when the file is closed, it should be automatically deleted.

The waitFor() method of the Process class will do the trick.

The API describes the method like below:

causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

[Source: http://java.sun.com/javase/6/docs/api/java/lang/Process.html]

The code is like below:

import java.io.File;
import java.io.IOException;

public class Test {
public static void main(String[] args) throws Exception {
try {
Process pc = Runtime.getRuntime().exec("C:/WINDOWS/ServicePackFiles/i386/notepad.exe C:/CheckDemo.txt");
try {
pc.waitFor();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
File file = new File("C:/CheckDemo.txt");
file.delete();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

No comments:

Total Pageviews