自定义字符输入流的包装类,通过这个包装类对底层字符输入流进行包装,让程序通过这个包装类读取某个文本文件(例如,一个java源文件)时,能够在读取的每行前面都加上有行号和冒号。
public class Test5 {
public static void main(String[] arg) {
Reader textReader = null;
try {
textReader=new FileReader("ForTest5Read.txt");
packStringStream pss=new packStringStream(textReader);
String toprint;
while ((toprint=pss.packedReadline())!=null) {
System.out.println(toprint);
}
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
System.out.println("读取失败可能文件不存在");
}
catch (IOException e) {
System.out.println("文件读取失败");
}
finally
{
if (textReader!=null) {
try {
textReader.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
System.out.println("文件关闭失败");
}
}
}
}
}
class packStringStream
{
BufferedReader br;
Integer count=0;
public packStringStream(Reader r) {
br=new BufferedReader(r);
}
public String packedReadline() throws IOException {
String string=null;
StringWriter sw=new StringWriter();
if((string=br.readLine())!=null) {
count++;
sw.write(count.toString());
sw.write(":");
sw.write(string);
}
else {
return null;
}
return sw.toString();
}
} |
|