Search code examples
javafile-handlingr.java-filereadfile

Generate Event after reading file


I want to raise the some event in Java after finishing the reading of file so that the handler can catch the event and proceed to next task .I am not able to find the existing event in Java which raise after finishing the reading of file.

is their any way to do so,or any other alternative for that.


Solution

  • You can use Observer Design Pattern.

    The Class that initiates the reading of file and will get the notification after the file is read.

    public class MainClass implements Observer
    {
        public static void main(String[] args) 
        {
            ReadFile rf = new ReadFile();
    
            MainClass mainClass = new MainClass();
    
            rf.addObserver(mainClass);
    
            rf.readFile();
        }
    
        @Override
        public void update(Observable o, Object arg)
        {
            // This method will be called after the File is finished reading.
        }
    }
    

    Class that will read the file and after the reading it will notify the Observers that the file reading is finished.

    public class ReadFile extends Observable 
    {
        public void readFile()
        {
            // ...
            // After reading file.
            notifyObservers();
        }
    }