Java code for tail n lines of file equivalent to tail commad in unix
<p>Following is the code written for tailing 'n' no of lines of a file.</p>

<pre><code> &lt;code&gt;

import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

class TailCommand {
public static void main(String args[]) {
    int j;
    try {
        /*
         * Receive file name and no of lines to tail as command line
         * argument
         */
        RandomAccessFile randomFile = new RandomAccessFile(args[0], "r");
        long numberOfLines = Long.valueOf(args[1]).longValue();
        long lineno = 0;
        String str;
        String outstr;
        StringBuilder sb = new StringBuilder();
        Map&lt;Long, String&gt; strmap = new HashMap&lt;Long, String&gt;();
        while ((str = randomFile.readLine()) != null) {
            strmap.put(lineno + 1, str);
            lineno++;
        }
        System.out.println("Total no of lines in file is " + lineno);
        long startPosition = lineno - numberOfLines;
        while (startPosition &lt;= lineno) {
            if (strmap.containsKey(startPosition)) {
            // System.out.println("HashMap contains "+  startPosition
                // +" as key");
                outstr = (String) strmap.get(startPosition);
                sb.append(outstr);
                System.out.println(outstr);
            }
            startPosition++;
        }
        // Collection coll = strmap.values();
        // System.out.println(coll+"size"+strmap.size());
        // System.out.println(sb);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}
</code></pre>

<p></p>

<p>I used the following approach:
The File and no of lines to be tailed is received as a command line argument</p>

<ol>
<li>use readLine method to get the total no of lines in a file</li>
<li>use a incrementer for each readLine call</li>
<li>Store this incrementer and string returned by readLinemethod in a Hash Map</li>
<li>As a result whole file is stored in Hash Map</li>
<li>Now you can use the hash map key to retrieve values of files from a specific line no</li>
<li>You can use stringbuilder to print the selection from particular line</li>
</ol>

<p>My doubts,</p>

<p>Is my approach valid, and can i use this approach for large files of size greater than 10MB ?
what improvements i need to make if more people has to tail simultaneously from same file?
May I use StringBuilder for larger files also?</p>
