Create a LineNumberReader like this
public class LineNumberReader extends BufferedReader { int lineNo = 1; public LineNumberReader(Reader in) { super((BufferedReader)in); } public void close() throws IOException { in.close(); } /* * Add more responsibility of adding a line Number in the beginning */ @Override public String readLine() throws IOException { String line = super.readLine(); if(line==null) return line; line = lineNo + ":" + line; lineNo++; return line; } }
Use the code as follows
public static void main(String[] args) throws FileNotFoundException { File file = new File("D:\\Yogesh.txt"); BufferedReader bufr = new BufferedReader(new FileReader(file)); BufferedReader lnr = new LineNumberReader(bufr); Scanner sc ; String line = ""; try { line=lnr.readLine(); while(line!=null) { System.out.println(line); line=lnr.readLine(); } } catch(Exception e) { e.printStackTrace(); } }
No comments:
Post a Comment