I just spent a lot of time tracking a bug where a file was not written and noticed that I delete the file after I created my FileOutputStream but before anything was written in it. I can understand that this is wrong, but why does it not throw an Exception to delete a file and then try to write on it?
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException
{
File test = new File("test.txt");
try(OutputStream out = new FileOutputStream(test))
{
if(test.exists()) {test.delete();}
out.write("Hello World".getBytes());
}
}
}
Is my Java installation broken?
My java -version
:
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)