java - 在尚未完成复制/上传时读取文件内容

标签 java file concurrency

每隔 5 秒(例如),服务器检查文件是否已添加到特定目录。如果是,它会读取并处理它们。相关文件可能很大(例如 100+ Mo),因此将它们复制/上传到上述目录可能会很长。

如果服务器试图访问尚未完成复制/上传的文件怎么办? JAVA 是如何管理这些并发访问的呢?是否取决于服务器的操作系统?


我试了一下,从远程服务器复制一个 ~1300000 行的 TXT 文件(即大约 200 Mo)到我的本地计算机:大约需要 5 秒。在此期间,我运行了以下 JAVA 类:

public static void main(String[] args) throws Exception {

    String local = "C:\\large.txt";

    BufferedReader reader = new BufferedReader(new FileReader(local));
    int lines = 0;
    while (reader.readLine() != null)
        lines++;
    reader.close();

    System.out.println(lines + " lines");

}

我得到以下异常:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Arrays.java:2882)
    at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:100)
    at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:515)
    at java.lang.StringBuffer.append(StringBuffer.java:306)
    at java.io.BufferedReader.readLine(BufferedReader.java:345)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    at main.Main.main(Main.java:15)

在文件复制完成后运行类时,我得到了预期的输出(即 1229761 行),因此异常不是由于文件的大小(我们可以先想想)。 JAVA 在后台做什么,引发了这个 OutOfMemoryError 异常?

最佳答案

How does JAVA manage these concurrent accesses? Does it depend on the OS of the server?

这取决于具体的操作系统。如果您在单个 JVM 中运行副本和服务器 AsynchronousFileChannel (new in 1.7)类可能会有很大的帮助。但是,如果客户端和服务器由不同的 JVM 表示(或者甚至更多,在不同的机器上启动),它就会变成特定于平台的。

来自 JavaDoc for AsynchronousFileChannel:

As with FileChannel, the view of a file provided by an instance of this class is guaranteed to be consistent with other views of the same file provided by other instances in the same program. The view provided by an instance of this class may or may not, however, be consistent with the views seen by other concurrently-running programs due to caching performed by the underlying operating system and delays induced by network-filesystem protocols. This is true regardless of the language in which these other programs are written, and whether they are running on the same machine or on some other machine. The exact nature of any such inconsistencies are system-dependent and are therefore unspecified.

关于java - 在尚未完成复制/上传时读取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15200396/

相关文章:

java - Hibernate 中的 SortedMap 键持久化

java - BatteryManager 健康值

security - Drupal 7 : how to restrict file access to specific user roles

java - ExecutorService.invokeAll 和关闭

java - 我应该怎么做才能防止 UI 卡住(scheduledexecutorservice)

java - 无法使用 jsch 运行 top 命令

java - 从 app-Engine 上的 java 类向 Android 客户端发送推送通知

python - 为什么 Python 和 wc 在字节数上不一致?

python - 如何将文件的大小和名称放入字典中

c++ - 了解 C++ 中放宽的内存顺序