Java I/O technology-custom LineNumberReader class

Source: Internet
Author: User

Package ioTest. io2;/** customize a decoration class for reading files with the method of reading row numbers */import java. io. fileReader; import java. io. IOException; import java. io. reader; public class MyLineNumberReaderDemo {public static void main (String [] args) throws IOException {String line; // create an input stream-Read File Information to the central stream, therefore, for the stream, FileReader in = new FileReader ("BufferedWriterDemo. java "); MyLineNumberReader mlnr = new MyLineNumberReader (in); while (line = mlnr. myReadLine ())! = Null) {System. out. println (mlnr. getLineNumber () + ":" + line);} mlnr. close () ;}// define a custom class similar to LineNumberReader MyLineNumberReader extends Reader {private Reader r; int lineNumber; int ch = 0; String line = null; // judging from the constructor, it is clear that this class is also a constructor class MyLineNumberReader (Reader r) {this. r = r;} public String MyReadLine () throws IOException {lineNumber ++; StringBuilder sBuilder = new StringBuilder (); while (ch = r. read ())! =-1) {if (ch = '\ n') continue; if (ch =' \ R') return sBuilder. toString (); elsesBuilder. append (char) ch);} if (sBuilder. length ()> 0) return sBuilder. toString (); return null;} public int getLineNumber () {return lineNumber;} public void setLineNumber (int lineNumber) {this. lineNumber = lineNumber;} @ Overridepublic int read (char [] cbuf, int off, int len) throws IOException {// TODO Auto-generated method stubreturn 0 ;} @ Overridepublic void close () throws IOException {// TODO Auto-generated method stubr. close ();}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.