I would like to know how to open a file in java for writing, but I only want to open it if it exists already. Is that possible? I've searched around and found two suggestions so far which both don't meet my needs. One was to open a file for appending. The problem there is that if the file doesn't exist it will create it. The second was to use file.exists() first. That of course is not a valid solution as the file may exist when I call file.exists() but then not exist when I go to open the file. I want something similar to the Windows API OpenFile() in which I can pass OPEN_EXISTING flag such that the call will fail is the file doesn't exists. Does anything like that exist in java?
Only editing question because it was marked duplicate. Not sure why. I thought I was pretty specific about the other answers and why they were not sufficient.
So I'll restate, I want to open a file for writing. I want the open to fail if the file doesn't already exist.
exists() returns true if the file path is a valid directory even if the file isn't there. You can get around this by using:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {/*Do whatever*/}
or use:
File f = new File(filePathString);
if f.isFile() {/*Do whatever*/}
Just catch the FileNotFoundException that is thrown:
try (FileInputStream fis = new FileInputStream(file))
{
// ...
}
catch (FileNotFoundException exc)
{
// it didn't exist.
}
Solutions involving File.exists() and friends are vulnerable to timing-window problems and therefore cannot be recommended. They also merely duplicate what the OS already has to do, but at the wrong time, so they are a waste of time and space. You have to deal with IOExceptions anyway, so do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With