Is there any way in java to read a file's content, which is being updated by another handler before closing it?
- 2Is this inside a single JVM? What is the underlying reason you need to do this - what problem are you solving?Thorbjørn Ravn Andersen– Thorbjørn Ravn Andersen2011-07-27 09:29:23 +00:00Commented Jul 27, 2011 at 9:29
- 2Why not just establish a direct stream between those 2 handlers?TC1– TC12011-07-27 09:33:14 +00:00Commented Jul 27, 2011 at 9:33
- 1agreed with Thorbjørn Ravn Andersen and others's comment - you need to talk about the actual underlying problem you have, not what you think a solution is (and then ask how to implement that solution). Chances are there are already ways of doing what you want to achieve in the end without going through it the way you have asked. I suspect you want to perform inter-process communications, but i m just having a wild guess.Chii– Chii2011-07-27 09:51:34 +00:00Commented Jul 27, 2011 at 9:51
2 Answers
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.
Comments
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?