-3

If I would like to check whether file exists or not I will use:

File file = new File("name of File");
if(file.exists()) { //do something}

But what shall i do, If I would like to use it as check of installation: file can be created e.g. after 5 or 10 minutes : so how can file.exists() controls whether file exists or not yet?

E.G.

  • Installation started, file doesn't exist
  • Installation continue 5 min file still doesnt exist
  • After 10 min - file was created - e.g. Installation.chk (file exists already) my if statement is now true

Is it possible to create it in Java? If yes, how?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
DRastislav
  • 1,892
  • 3
  • 26
  • 40

2 Answers2

1

Maybe there is a better way:

http://docs.oracle.com/javase/tutorial/essential/io/notification.html

Instead of looping your exists(), let the OS tell you, if something changes.

desperateCoder
  • 700
  • 8
  • 18
0

When dealing with the file-system you have to accept that race-conditions happen and plan for them.

You can only check whether a file exists now, not whether it will continue to exist because disks can be mounted/ejected, super-user accounts can delete files or unlink or make parent directories unreadable.

java.io does not support file-locking either.

If you need to check that something is installed, you can make a best effort, but you cannot prevent a user from uninstalling another piece of software while yours is running.


if(file.exists()) { /*do something*/}

This is rarely useful by itself.

Often, combining a file type and a permissions check identifies more bad states than just testing existence.

file.isFile() && file.canRead()
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • @Amalgovinus, are you sure? It has to read through directories, and may have to read through symlinks depending on the LinkOptions, but I don't see anything in the doc to suggest that it will check read permissions on a normal file. – Mike Samuel Jun 20 '18 at 12:42