Monday, October 5, 2015

Java reading a file and printing the line number


Example to read a file through Scanner class and print number of lines in the file

INPUT file used (line.txt)


 package sudas.utils;  
 import java.io.FileInputStream;  
 import java.io.FileNotFoundException;  
 import java.util.Scanner;  
 public class LogHelper {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           new logScanner().scanIgnoreCase();  
      }  
 }  
 class logScanner {  
      String path = "C:/Test/line.txt";  
      int lineNumber;  
      public void scanIgnoreCase() {  
           try {  
                Scanner in = new Scanner(new FileInputStream(path));  
                int lineNum = 0;  
                while (in.hasNextLine()) {  
                     String nextline = in.nextLine();  
                     System.out.println(nextline);  
                     System.out.println(lineNum++);  
                }  
           } catch (FileNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  
OUTPUT

Apple
0
Banana
1
Orange
2
Grapes
3
Rose
4
Lily
5
Dog
6
Cat
7

Example to read a file through LineNumberReader class and print number of lines in the file



 package LineReader;  
 import java.io.FileReader;  
 import java.io.IOException;  
 import java.io.LineNumberReader;  
 public class GetLineNumber {  
      public static void main(String[] args) {  
           new GetLineNumber().getLineNumber();  
      }  
      public void getLineNumber() {  
           try {  
                LineNumberReader linereader = new LineNumberReader(new FileReader("C:/Test/line.txt"));  
                int reader;  
                while ((reader = linereader.read()) != -1) {  
                     // String contents =linereader.readLine();  
                     // System.out.println(contents);  
                     char c = (char) reader;  
                     System.out.print(c);  
                     if (c == '\n') {  
                          System.out.println(linereader.getLineNumber());  
                     }  
                }  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
      }  
 }  
OUTPUT

Apple
1
Banana
2
Orange
3
Grapes
4
Rose
5
Lily
6
Dog
7
Cat

No comments:

Post a Comment