How to read a text file when lines are added

advertisements

I have been asked to write a program that will read a file as it is updated (4 times/millisecond) and print the number of lines to the system. To do this, I have the following code:

     package threadFile;
    import java.io.IOException;
    import java.io.FileReader;

    import java.io.BufferedReader;

public class ReadFile
{
private String path;

    public ReadFile(String file_name)
    {
        path = file_name;
    }

    public String[] OpenFile() throws IOException
    {
        FileReader fr = new FileReader(path);
        BufferedReader textReader = new BufferedReader(fr);

        int numberOfLines = readLines();
        String[]textData = new String[numberOfLines];

        int i;
        for(i=0; i< numberOfLines; i++)
        {
            textData[i] = textReader.readLine();
        }
        textReader.close();
        return textData;
    }

    @SuppressWarnings("unused")
    int readLines() throws IOException
    {
        FileReader file_to_read = new FileReader(path);
        BufferedReader bf = new BufferedReader(file_to_read);

        String aLine;
        int numberOfLines = 0;

        while ((aLine = bf.readLine()) != null)
        {
            numberOfLines++;
        }
        bf.close();

        return numberOfLines;
    }

The above code is meant to open a text file and read the number of lines there are. My issue is, getting the program to update as the file is written to (by another section of the program).The below code is a thread, and is meant to call into ReadFile for instructions. I need the program to constantly read the contents, and accurately update the line count as it is edited.


If I understand correctly your requirement you want to use one file for Inter Process Communication (or inter thread-communication to be more exact for your case). If this is the case you probably want to use the file as MemoryMapped file.

A simple description of MemoryMapped file usage is done here.

As it was already said, Java 1.7 Watch Service is also a solution that could work.