I have the following Groovy test script:
def dir = new File("test")
dir.mkdirs()
char[] data = new char[100]
Arrays.fill(data, (char)'q')
for(i in 0..1760){
def file = new File(dir, "file$i")
file.createNewFile()
file.withOutputStream { os ->
os << data
}
}
def delete (File f){
if(f.isDirectory()){
for(File afile : f.listFiles()){
delete(afile);
}
f.delete();
}else{
f.delete();
}
}
delete(dir)
dir.mkdirs()
new File(dir, "file").createNewFile() //<-- java.io.IOException: Access is denied
Which fails with:
Caught: java.io.IOException: Access is denied
java.io.IOException: Access is denied
at java_io_File$createNewFile.call(Unknown Source)
at test.run(test.groovy:29)
However, if I amend the test script to look like this:
def dir = new File("test")
dir.mkdirs()
char[] data = new char[100]
Arrays.fill(data, (char)'q')
for(i in 0..1760){
def file = new File(dir, "file$i")
file.createNewFile()
file.withOutputStream { os ->
os << data
}
}
def delete (File f){
if(f.isDirectory()){
for(File afile : f.listFiles()){
delete(afile);
}
f.delete();
}else{
f.delete();
}
}
delete(dir)
Thread.sleep(1000) // <---- added a 1 second pause after deleting
dir.mkdirs()
new File(dir, "file").createNewFile() // <-- No Exception
It will no longer fail. I am running Java 6 on Windows 7 64-bit. Anyone have any idea where the delay comes from or how to account for it?
Edit:
Same error happens in Java 6 which is why I tagged it Java (Groovy is just easier to write an example in). Here is the equivalent test which also fails in Java:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class Test {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
new Test().execute();
}
public void execute() throws IOException{
File dir = new File("test");
dir.mkdirs();
char[] data = new char[100];
Arrays.fill(data, (char)'q');
for(int x = 0; x < 1760; x++){
File file = new File(dir, "file" + x);
file.createNewFile();
FileWriter fw = null;
try{
fw = new FileWriter(file);
fw.write(data);
}finally{
if(fw != null){
fw.close();
}
}
}
delete(dir);
dir.mkdirs();
new File(dir, "file").createNewFile(); //<-- java.io.IOException: Access is denied
}
private void delete (File f){
if(f.isDirectory()){
for(File afile : f.listFiles()){
delete(afile);
}
f.delete();
}else{
f.delete();
}
}
}