ARUP BAROI ARUP BAROI - 2 months ago 7
Java Question

Log file auto monitoring in java which is incriminating in every time and always want to monitor new line

I have a log file which is increasing always due to logging for different logging event in my application. Now i want to check some patterns in the log file and if I find any match for the patterns I will print it some where else. The log file is not static file it is always increasing and I my program should not check the old line again. It should always checks the new line which have not been checked yet.

Answer

Store the position of what you have checked up to in some kind of integer or file. now when you look for a pattern look for a regular expression and then print it to whatever output stream.

First read the file into an array like so, call the getWordsFromFile() method.

/**
 *
 * @param fileName is the path to the file or just the name if it is local
 * @return the number of lines in fileName
 */
public static int getLengthOfFile(String fileName) {
    int length = 0;
    try {
        File textFile = new File(fileName);
        Scanner sc = new Scanner(textFile);
        while (sc.hasNextLine()) {
            sc.nextLine();
            length++;
        }
    } catch (Exception e) {

    }
    return length;
}

/**
 *
 * @param fileName is the path to the file or just the name if it is local
 * @return an array of Strings where each string is one line from the file
 * fileName.
 */
public static String[] getWordsFromFile(String fileName) {
            int lengthOfFile = getLengthOfFile(fileName);
    String[] wordBank=new String[lengthOfFile];
    int i = 0;
    try {
        File textFile = new File(fileName);
        Scanner sc = new Scanner(textFile);
        for (i = 0; i < lengthOfFile; i++) {
        wordBank[i] = sc.nextLine();
        }
        return wordBank;
    } catch (Exception e) {
                System.err.println(e);
        System.exit(55);
    }
    return null;
}

For larger files see this question Then once you load your String[], you can iterate through like so.

for(int i=0;i<arr.length;i++) 
doSomething(arr[i]);

to something like

for(int i= start;i<arr.length;i++)
doSomething(arr[i]);
Comments