Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only open an existing file in java [duplicate]

Tags:

java

file

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.


2 Answers

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*/}
like image 177
javawocky Avatar answered Nov 02 '25 11:11

javawocky


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.

like image 32
user207421 Avatar answered Nov 02 '25 11:11

user207421