'Avoid file system caching with RandomAccessFile

For a crude live monitor app, I am polling a huge file on a network share using RandomAccessFile. Another application is writing data to that file and my aim is to read the last couple of bytes that were written to the file in order to do some live monitoring. In doing so, I am facing the problem that Windows, Java or my NAS seem to cache the file upon first access (anecdotal evidence), which is not suitable for me. Even though I close the file each time after reading it, reopening it later returns me the exact same data which I hhave already read (randomAccessFile.length() stays constant even though the other application is writing to it).

For my application, I always need the most up to date version of the file everytime I open it. Hence my question: How can I avoid this caching?

Here's my minimal code sample:

private fun streamNextFrame(): Unit = Thread {
    val currentFolder = File("/folder/that/contains/files")

    val fileList = currentFolder.listFiles()?.toList() ?: return

    val latestFile = fileList.sortWithNaturalOrder().lastOrNull()
    if (latestFile == null) {
        logger.info("No file to stream found")
        Platform.runLater { if (isStreaming) streamNextFrame() }
        return
    }

    val randomAccessFile = RandomAccessFile(latestFile, "r")

    randomAccessFile.seek(0)
    
    // read and parse the file

    randomAccessFile.close()

    Platform.runLater {
        if (isStreaming) streamNextFrame()
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source