<p>I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time.</p>

<p>I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then? </p>

<p>My intuition is currently pushing me towards BufferedStreams. Is this the way to go?</p>

[{'answer_id': 4188, 'author': 'Matthew Schinckel', 'author_id': 188, 'author_profile': 'https://Stackoverflow.com/users/188', 'pm_score': 1, 'selected': False, 'text': "<p>Not Java per-se, but you may run into issues where you have written something to a file, but it hasn't been actually written yet - it might be in a cache somewhere, and reading from the same file may not actually give you the new information.</p>\n\n<p>Short version - use flush() or whatever the relevant system call is to ensure that your data is actually written to the file.</p>\n\n<p>Note I am not talking about the OS level disk cache - if your data gets into here, it should appear in a read() after this point.  It may be that the language itself caches writes, waiting until a buffer fills up or file is flushed/closed.</p>\n"}, {'answer_id': 4206, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 0, 'selected': False, 'text': "<p>I've never tried it, but you should write a test case to see if reading from a stream after you have hit the end will work, regardless of if there is more data written to the file.</p>\n\n<p>Is there a reason you can't use a piped input/output stream?  Is the data being written and read from the same application (if so, you have the data, why do you need to read from the file)?</p>\n\n<p>Otherwise, maybe read till end of file, then monitor for changes and seek to where you left off and continue... though watch out for race conditions.</p>\n"}, {'answer_id': 4498, 'author': 'Anthony Cramp', 'author_id': 488, 'author_profile': 'https://Stackoverflow.com/users/488', 'pm_score': 2, 'selected': False, 'text': '<p>The answer seems to be "no" ... and "yes". There seems to be no real way to know if a file is open for writing by another application. So, reading from such a file will just progress until content is exhausted. I took Mike\'s advice and wrote some test code:</p>\n\n<p>Writer.java writes a string to file and then waits for the user to hit enter before writing another line to file. The idea being that it could be started up, then a reader can be started to see how it copes with the "partial" file. The reader I wrote is in Reader.java.</p>\n\n<p><strong>Writer.java</strong></p>\n\n<pre><code>public class Writer extends Object\n{\n    Writer () {\n\n    }\n\n    public static String[] strings = \n        {\n            "Hello World", \n            "Goodbye World"\n        };\n\n    public static void main(String[] args) \n        throws java.io.IOException {\n\n        java.io.PrintWriter pw =\n            new java.io.PrintWriter(new java.io.FileOutputStream("out.txt"), true);\n\n        for(String s : strings) {\n            pw.println(s);\n            System.in.read();\n        }\n\n        pw.close();\n    }\n}\n</code></pre>\n\n<p><strong>Reader.java</strong></p>\n\n<pre><code>public class Reader extends Object\n{\n    Reader () {\n\n    }\n\n    public static void main(String[] args) \n        throws Exception {\n\n        java.io.FileInputStream in = new java.io.FileInputStream("out.txt");\n\n        java.nio.channels.FileChannel fc = in.getChannel();\n        java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10);\n\n        while(fc.read(bb) &gt;= 0) {\n            bb.flip();\n            while(bb.hasRemaining()) {\n                System.out.println((char)bb.get());\n            }\n            bb.clear();\n        }\n\n        System.exit(0);\n    }\n}\n</code></pre>\n\n<p>No guarantees that this code is best practice.</p>\n\n<p>This leaves the option suggested by Mike of periodically checking if there is new data to be read from the file. This then requires user intervention to close the file reader when it is determined that the reading is completed. Or, the reader needs to be made aware the content of the file and be able to determine and end of write condition. If the content were XML, the end of document could be used to signal this.</p>\n'}, {'answer_id': 38133, 'author': 'Frederic Morin', 'author_id': 4064, 'author_profile': 'https://Stackoverflow.com/users/4064', 'pm_score': 3, 'selected': False, 'text': '<p>You might also take a look at java channel for locking a part of a file.</p>\n\n<p><a href="http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html" rel="noreferrer">http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html</a></p>\n\n<p>This function of the <code>FileChannel</code> might be a start</p>\n\n<pre><code>lock(long position, long size, boolean shared) \n</code></pre>\n\n<p>An invocation of this method will block until the region can be locked</p>\n'}, {'answer_id': 154588, 'author': 'Joseph Gordon', 'author_id': 1741, 'author_profile': 'https://Stackoverflow.com/users/1741', 'pm_score': 7, 'selected': True, 'text': '<p>Could not get the example to work using <code>FileChannel.read(ByteBuffer)</code> because it isn\'t a blocking read. Did however get the code below to work:</p>\n\n<pre><code>boolean running = true;\nBufferedInputStream reader = new BufferedInputStream(new FileInputStream( "out.txt" ) );\n\npublic void run() {\n    while( running ) {\n        if( reader.available() &gt; 0 ) {\n            System.out.print( (char)reader.read() );\n        }\n        else {\n            try {\n                sleep( 500 );\n            }\n            catch( InterruptedException ex ) {\n                running = false;\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>Of course the same thing would work as a timer instead of a thread, but I leave that up to the programmer. I\'m still looking for a better way, but this works for me for now.</p>\n\n<p>Oh, and I\'ll caveat this with: I\'m using 1.4.2. Yes I know I\'m in the stone ages still.</p>\n'}, {'answer_id': 28818516, 'author': 'Rodrigo Menezes', 'author_id': 1255493, 'author_profile': 'https://Stackoverflow.com/users/1255493', 'pm_score': 2, 'selected': False, 'text': '<p>There are a Open Source Java Graphic Tail that does this.</p>\n\n<p><a href="https://stackoverflow.com/a/559146/1255493">https://stackoverflow.com/a/559146/1255493</a></p>\n\n<pre><code>public void run() {\n    try {\n        while (_running) {\n            Thread.sleep(_updateInterval);\n            long len = _file.length();\n            if (len &lt; _filePointer) {\n                // Log must have been jibbled or deleted.\n                this.appendMessage("Log file was reset. Restarting logging from start of file.");\n                _filePointer = len;\n            }\n            else if (len &gt; _filePointer) {\n                // File must have had something added to it!\n                RandomAccessFile raf = new RandomAccessFile(_file, "r");\n                raf.seek(_filePointer);\n                String line = null;\n                while ((line = raf.readLine()) != null) {\n                    this.appendLine(line);\n                }\n                _filePointer = raf.getFilePointer();\n                raf.close();\n            }\n        }\n    }\n    catch (Exception e) {\n        this.appendMessage("Fatal error reading log file, log tailing has stopped.");\n    }\n    // dispose();\n}\n</code></pre>\n'}, {'answer_id': 32783641, 'author': 'ToYonos', 'author_id': 2003986, 'author_profile': 'https://Stackoverflow.com/users/2003986', 'pm_score': 3, 'selected': False, 'text': '<p>I totally agree with <a href="https://stackoverflow.com/a/10803105/2003986">Joshua\'s response</a>, <a href="https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/input/Tailer.html" rel="nofollow noreferrer">Tailer</a> is fit for the job in this situation. Here is an example :</p>\n\n<p>It writes a line every 150 ms in a file, while reading this very same file every 2500 ms</p>\n\n<pre><code>public class TailerTest\n{\n    public static void main(String[] args)\n    {\n        File f = new File("/tmp/test.txt");\n        MyListener listener = new MyListener();\n        Tailer.create(f, listener, 2500);\n\n        try\n        {\n            FileOutputStream fos = new FileOutputStream(f);\n            int i = 0;\n            while (i &lt; 200)\n            {\n                fos.write(("test" + ++i + "\\n").getBytes());\n                Thread.sleep(150);\n            }\n            fos.close();\n        }\n        catch (Exception e)\n        {\n            e.printStackTrace();\n        }\n    }\n\n    private static class MyListener extends TailerListenerAdapter\n    {\n        @Override\n        public void handle(String line)\n        {\n            System.out.println(line);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 32851944, 'author': 'tiger.spring', 'author_id': 4042626, 'author_profile': 'https://Stackoverflow.com/users/4042626', 'pm_score': 4, 'selected': False, 'text': '<p>If you want to read a file while it is being written and only read the new content then following will help you achieve the same.</p>\n\n<p>To run this program you will launch it from command prompt/terminal window and pass the file name to read. It will read the file unless you kill the program.</p>\n\n<p>java FileReader c:\\myfile.txt</p>\n\n<p>As you type a line of text save it from notepad and you will see the text printed in the console.</p>\n\n<pre><code>public class FileReader {\n\n    public static void main(String args[]) throws Exception {\n        if(args.length&gt;0){\n            File file = new File(args[0]);\n            System.out.println(file.getAbsolutePath());\n            if(file.exists() &amp;&amp; file.canRead()){\n                long fileLength = file.length();\n                readFile(file,0L);\n                while(true){\n\n                    if(fileLength&lt;file.length()){\n                        readFile(file,fileLength);\n                        fileLength=file.length();\n                    }\n                }\n            }\n        }else{\n            System.out.println("no file to read");\n        }\n    }\n\n    public static void readFile(File file,Long fileLength) throws IOException {\n        String line = null;\n\n        BufferedReader in = new BufferedReader(new java.io.FileReader(file));\n        in.skip(fileLength);\n        while((line = in.readLine()) != null)\n        {\n            System.out.println(line);\n        }\n        in.close();\n    }\n}\n</code></pre>\n'}, {'answer_id': 34576387, 'author': 'bebbo', 'author_id': 1412279, 'author_profile': 'https://Stackoverflow.com/users/1412279', 'pm_score': 2, 'selected': False, 'text': "<p>You can't read a file which is opened from another process using FileInputStream, FileReader or RandomAccessFile.</p>\n\n<p>But using FileChannel directly will work:</p>\n\n<pre><code>private static byte[] readSharedFile(File file) throws IOException {\n    byte buffer[] = new byte[(int) file.length()];\n    final FileChannel fc = FileChannel.open(file.toPath(), EnumSet.of(StandardOpenOption.READ));\n    final ByteBuffer dst = ByteBuffer.wrap(buffer);\n    fc.read(dst);\n    fc.close();\n    return buffer;\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/4149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/488/']