Friday, 13 July 2012

Count and Display non empty lines in a file Java

Count and Display nun empty lines in a file Java

public class FileLineCounter
{
    public static int countAndDisplayNonEmptyLines(String path) throws IOException
    {
        int lineCount = 0;
        InputStream is = null;
        try
        {
            is = new FileInputStream(path);
            InputStreamReader in = new InputStreamReader(is);
            BufferedReader _input = new BufferedReader(in);

            String line = _input.readLine();
            while ( line != null )
            {
                if ( !line.trim().isEmpty() )
                {
                    System.out.println(lineCount + ". " + line);
                    lineCount++;
                }
                line = _input.readLine();
            }
        }
        finally
        {
            if ( is != null )
                is.close();
        }
        return lineCount;
    }

    public static void main(String args[])
    {
        try
        {
            countAndDisplayNonEmptyLines("C:\\Users\\Desktop\\help.log");
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment