sekar
sekar

Reputation: 21

Java - How to read and write a file simultaneously?

Is there any way in java to read a file's content, which is being updated by another handler before closing it?

Upvotes: 2

Views: 2585

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533890

In theory its quite easy to do, however files are not designed to exchange data this way and depending on your requirements it can be quite tricky to get right. This is why there is no general solution for this.

e.g. if you want to read a file as another process writes to it, the reading thread will see an EOF even though the writer hasn't finished. You have to re-open the file and skip to where the file was last read and continue. The writing thread might roll the files it is writing meaning the reading has to detect this and handle it.

What specificity do you want to do?

Upvotes: 2

Joachim Sauer
Joachim Sauer

Reputation: 308269

That depends on the operating systems.

Traditionally, POSIX-y operating systems (Linux, Solaris, ...) have absolutely no problem with having a file open for both reading and writing, even by separate processes (they even support deleting a file while it's being read from and/or written to).

In Windows, the more common approach is to open files exclusively (contrary to common believe, Windows does support non-exclusive file access, it's just rarely used by applications).

Java has no way* of specifying what way you want to access a file, so the platform default is used (shared access on Linux/Solaris, exclusive access on Windows).

* This might be wrong for NIO and new NIO in Java 7, but I'm not a big NIO expert.

Upvotes: 4

Related Questions