java readline linux,Java 对readLine扩展添加行号样式

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

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

2 //需要导入的一些包

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.io.Reader;

//使用继承的方法,对BufferedReader类的readline()方法进行扩展

//自定义一个继承BufferedReader的类

class BufferedRLN extends BufferedReader{

int count = 0;

//构造方法,使用父类的参数

public BufferedRLN(Reader in){

super(in); //

}

@Override

public String readLine() throws IOException {

//调用父类的readline()方法,返回一行数据

String content = super.readLine();

//给返回的数据设置样式(这里添加行号)

if (content == null) {

return null; //如果为空,数据已经读完

}

content = count+" "+content; //添加行号

count++;

return content;

}

}

public class readline {

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

File file = new File("C:\\Users\\lx\\Desktop\\io作业.txt");

readlineExt1(file);

}

//使用自定义类 BufferedRLN

public static void readlineExt1(File file) throws IOException{

FileReader frd = new FileReader(file);

//这里的 实际参数 frd 将传到自定义里的构造方法里

BufferedRLN bfrd = new BufferedRLN(frd);

//读取数据

String string = null;

while ((string = bfrd.readLine()) != null) {

System.out.println(string);

}

//关闭资源

frd.close();

}

0b1331709591d260c1c78e86d0c51c18.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值