简体   繁体   中英

Java - How to read and write a file simultaneously?

java中有什么方法可以读取文件的内容,该内容在关闭文件之前由另一个处理程序进行更新?

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.

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.

eg 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM