Reputation: 93
I know the basic syntax for creating and deleting directories. I am in a strange situation, so any help will be really helpful.
I create the directories as shown below:
if (!dir.exists()) {
dir.mkdir();
}
else
System.out.println("hfuiwedsjcz");
I create a directory, and inside the directory I have more than one file. I write to those files and perform several operations on the files inside the directory.
I want to write a program to create the directory, such as the directory is deleted after I have written and read the files inside it (So as to avoid deleting the folder manually).
I am assuming it is a recursive process, where I first create folder and then delete it. Now when I run the next time, I should not be having any folder, rather it should be created again and deleted in the end.
How would I do this?
Upvotes: 1
Views: 374
Reputation: 8606
How about just presume that the directory will be once created and at every run, at the end you would just clean-up the directory (empty the directory)? This might help you:
Or as you wish, you can go for:
And at the end either:
FileUtils.deleteDirectory() or
This is similar to what the other people responded, but this would be the easier way of going if you are using jdk 1.6 and not 1.7 (unfortunately, there a lot of people still using 1.6)
Upvotes: 1
Reputation: 2189
Use java.io.File.deleteOnExit()
on each created File object. You need to start from the first directory, you create and call it for every used File
object.
Upvotes: 0
Reputation: 69339
One option would be to use the deleteOnExit()
method from the File
class. Invoke this on each directory and file as you create them.
It will delete the files when the JVM exists in the reverse order that you registered the files.
if (!dir.exists()) {
dir.mkdir();
dir.deleteOnExit();
}
// etc...
Upvotes: 5