- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.Reader;
- public class Test {
- /**
- * @param args
- * @throws IOException
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //建立MyLineNumberReader对象
- MyLineNumberReader mylnr = null;
- try {
- mylnr = new MyLineNumberReader(new FileReader("F:\\workspace\\exam\\src\\com\\itheima\\Test7.java"));
- String line = null;
- while((line=mylnr.myReadLine())!=null){
- System.out.println(mylnr.getLineNumber()+":"+line);
- }
-
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally{
- try {
- if(mylnr!=null)
- mylnr.myClose();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- //自定义一个字符输入流包装类,带行号
- class MyLineNumberReader{
- private Reader r;
- private int lineNumber;
- MyLineNumberReader(Reader r){
- this.r = r;
- }
-
- public String myReadLine() throws IOException{
- lineNumber++;
- //定义一个容器存放数据
- StringBuilder sb = new StringBuilder();
- int ch = 0;
- while((ch=r.read())!=-1){
- if(ch=='\r')
- continue;
- if(!(ch=='\n'))
- sb.append((char)ch);
- else
- return sb.toString();
- }
- if(sb.length()!=0)
- return sb.toString();
- return null;
- }
-
- //获取行号
- public int getLineNumber() {
- return lineNumber;
- }
- //设置行号
- public void setLineNumber(int lineNumber) {
- this.lineNumber = lineNumber;
- }
- //关闭流
- public void myClose() throws IOException{
- r.close();
- }
- }
复制代码 |