zoukankan      html  css  js  c++  java
  • java 对readLine扩展添加行号样式

    java 的流的使用中,在字符缓冲输入流中,有一个每次读取一行数据的方法:readLine();

    在这里使用简单的继承方法对其继续扩展,使得返回每行前面添加序号

     1  2 //需要导入的一些包
     3 import java.io.BufferedReader;
     4 import java.io.File;
     5 import java.io.FileReader;
     6 import java.io.IOException;
     7 import java.io.Reader;
     8 
     9 //使用继承的方法,对BufferedReader类的readline()方法进行扩展
    10 
    11 //自定义一个继承BufferedReader的类
    12 class BufferedRLN extends BufferedReader{
    13     int count = 0;
    14     //构造方法,使用父类的参数
    15     public BufferedRLN(Reader in){
    16         super(in); //
    17     }
    18     
    19     @Override
    20     public String readLine() throws IOException {        
    21         //调用父类的readline()方法,返回一行数据
    22         String content = super.readLine();
    23         //给返回的数据设置样式(这里添加行号)
    24         if (content == null) {
    25             return null; //如果为空,数据已经读完
    26         }
    27         content = count+" "+content; //添加行号
    28         count++;
    29         return content;
    30     }
    31 }
    32 
    33 
    34 public class readline {
    35     public static void main(String[] args) throws IOException {
    36         // TODO Auto-generated method stub
    37         File file = new File("C:\Users\lx\Desktop\io作业.txt");
    38     
    39         readlineExt1(file);
    40     } 
    41         
    42     //使用自定义类 BufferedRLN
    43     public static void readlineExt1(File file) throws IOException{
    44         
    45         FileReader frd = new FileReader(file);
    46         //这里的 实际参数 frd 将传到自定义里的构造方法里
    47         BufferedRLN bfrd = new BufferedRLN(frd);
    48         //读取数据
    49         String string = null;
    50         while ((string = bfrd.readLine()) != null) {
    51             System.out.println(string);    
    52         }
    53         //关闭资源
    54         frd.close();
    55     } 
    56 
    57 
  • 相关阅读:
    AtCoder Grand Contest 032-B
    AtCoder Grand Contest 032 A
    高橋君とカード / Tak and Cards AtCoder
    Divisibility by 25 CodeForces
    Fire Again CodeForces
    cctype函数 (字符类型判断)
    蓝桥杯--- 历届试题 国王的烦恼 (并查集)
    蓝桥杯---买不到的数目
    算法课(经典贪心)
    完美的数字
  • 原文地址:https://www.cnblogs.com/bigerf/p/6143370.html
Copyright © 2011-2022 走看看