简体   繁体   English

多个Java进程可以同时读取同一个文件吗?

[英]Can multiple Java processes read the same file at the same time?

Is it possible to read the same file from two or more different processes at the same time? 是否可以同时从两个或多个不同的进程读取同一个文件?

I'd like to do something like this in a Java application: 我想在Java应用程序中做这样的事情:

final File f = new File("read-only-file");
final FileInputStream in = new FileInputStream(f);
int b;
while((b = in.read()) != null) {
    //process b
    Thread.sleep(10); //several read processes would really happen at the same time
}

No application would ever write to the file but several threads/applications need to execute the code above at the same time. 没有应用程序会写入文件,但是多个线程/应用程序需要同时执行上面的代码。 Is the code above fine or do I need to use any special mechanisms in that case? 代码是否正常或在这种情况下是否需要使用任何特殊机制?

Also the solution should be platform-independent and must work on Linux like systems. 该解决方案也应该是独立于平台的,并且必须在类似Linux的系统上运行。

Can multiple Java processes read the same file at the same time? 多个Java进程可以同时读取同一个文件吗?

Sure they can; 当然可以; and ultimately, it is the role of the OS anyway to ensure that each process/thread reads at its own pace, so you need not worry about it. 最后,无论如何,操作系统的作用是确保每个进程/线程按照自己的进度读取,因此您不必担心它。

Of course, you may want to share as many resources as possible between the different threads, but certainly not the I/O streams; 当然,您可能希望在不同的线程之间共享尽可能多的资源,但肯定不是I / O流; and while we are at it, use the new file API if you use Java 7 or upper (this is 2014; it's been 3 years since Java 7 is there); 当我们使用时,如果您使用Java 7或更高版本,则使用新文件API(这是2014年;自Java 7开始以来已经有3年了); File is a very inferior API compared to java.nio.file (and, in fact, compared to the file manipulation APIs of most programming languages in general). 与java.nio.file相比, File是一个非常低劣的API(事实上,与一般的大多数编程语言的文件操作API相比)。

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

相关问题 Java同时读取两个文本文件 - Java read two text file at the same time Java:多个线程同时读取同一InputStream - Java: multiple threads read the same InputStream at the same time Java和python进程可以独占锁定linux上的相同文件 - Java and python processes can exclusive lock the same file on linux Java是否可以触发同一事件多次并同时运行? - Java Can the same event be triggerd multiple times and be running at the same time? 我们可以同时打开多个 FileWriter stream 到同一个文件吗? - can we open multiple FileWriter stream to the same file at the same time? Java类允许多个线程读取或同时修改一个 - Java class to allow multiple threads to read or one to modify at the same time 如何在Java中同时读取多行作为输入 - how to read multiple lines as input at the same time in java 无法在Java中同时从文件读取对象和数据 - Not able to read object and data from the file at same time in java 如何在Java(Selenium)设置中使用Apache POI多个线程(并行测试用例)同时访问相同的excel文件? - How can multiple threads (parallel testcases) access same excel file at same time using Apache POI in Java (Selenium) setup? 使用相同的多个键读取.txt(属性)文件-Java - read .txt (properties) file with same multiple keys - java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM