Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Reading a File As It's Being Written

DZone's Guide to

Reading a File As It's Being Written

A brief code snippet that allows you to view a file as it's being written to a disc.

· Java Zone ·
Free Resource

Secure your Java app or API service quickly and easily with Okta's user authentication and authorization libraries. Developer accounts are free forever. Try Okta Instead.

The below code describes how to read a file when a particular file is actively being written. Here is a full example. For the below example the mentioned file should be existed in the mentioned path else it will throw FileNotFoundException.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadingFileWhileWrite extends Thread {

    boolean running = true;
    BufferedInputStream reader = null;

    public static void main(String[] args) throws FileNotFoundException {
        ReadingFileWhileWrite tw = new ReadingFileWhileWrite();
        tw.reader = new BufferedInputStream(new FileInputStream("TestFile.txt"));
        tw.start();
    }

    public void run() {
        while (running) {
            try {
                if (reader.available() > 0) {
                    System.out.print((char) reader.read());
                } else {
                    try {
                        sleep(500);
                    } catch (InterruptedException ex) {
                        running = false;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


For other posts please visit my blog : Journey Towards Java

Secure your Java app or API service quickly and easily with Okta's user authentication and authorization libraries. Developer accounts are free forever. Try Okta Instead.

Topics:
java ,j2ee

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}