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.
Join the DZone community and get the full member experience.
Join For FreeThe 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
Published at DZone with permission of Shidram BJ. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments