简体   繁体   English

Java-如何同时读取和写入文件?

[英]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). 传统上,POSIX-y操作系统(Linux,Solaris等)打开文件进行读写都绝对没有问题,即使是通过单独的进程(它们甚至支持在读取和/或读取文件时删除文件)写入)。

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). 在Windows中,更常见的方法是以独占方式打开文件(与通常的看法相反,Windows 确实支持非独占文件访问,应用程序很少使用它)。

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). Java无法*指定要访问文件的方式,因此使用平台默认值(在Linux / Solaris上为共享访问,在Windows上为互斥访问)。

* This might be wrong for NIO and new NIO in Java 7, but I'm not a big NIO expert. *这对于Java 7中的NIO和新的NIO可能是错误的,但是我不是NIO的专家。

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. 例如,如果您想在另一个进程写入文件时读取文件,则即使写入程序尚未完成,读取线程也会看到EOF。 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? 您想做什么特异性?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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