黑马程序员技术交流社区
标题:
包装
[打印本页]
作者:
游呤人
时间:
2015-7-18 01:21
标题:
包装
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
@SuppressWarnings("all")
/*
*自定义字符输入流的包装类,通过这个包装类对底层字符输入流进行包装,
*让程序通过这个包装类读取某个文本文件(例如,一个java源文件)时
*,定义一个开关当开关开启时能够在读取的每行前面都加上有行号,当关闭时就不在显示
*
* */
public class MyReader {
private String pathName; //路径名
private Reader read; //字符阅读流
private boolean lineNumber; //行号开关
private MyReader(){}
public MyReader(Reader reader) throws FileNotFoundException{
this(null,reader,false);
}
public MyReader(String pathName) throws FileNotFoundException{
this(pathName,null,false);
}
public MyReader(Reader reader,boolean lineNumber) throws FileNotFoundException{
this(null,reader,lineNumber);
}
private MyReader(String pathName,Reader read,boolean lineNumber) throws FileNotFoundException{
if(read==null&&pathName==null){ //字符流为空,或者pathName为空都无法创建此流
throw new NullPointerException("pathName or read is Null");
}else if(pathName!=null){
this.read=new FileReader(pathName);
this.lineNumber=lineNumber;
}else{
this.read=read;
this.lineNumber=lineNumber;
}
}
public void setLineNumbr(boolean lineNumber){
this.lineNumber=lineNumber;
}
private String readLine() throws IOException{
int buff=0;
StringBuilder strbuff=new StringBuilder(); //开始阅读一行数据.
while((buff=read.read())!=-1){
if(buff=='\r'){
continue;
}
if(buff=='\n'){
return strbuff.toString();
}
strbuff.append((char)buff);
}
return null;
}
public String[] readFile() { //读取整个文件
int num=1;
String line="";
ArrayList<String> list=new ArrayList<String>();
try {
while((line=readLine())!=null){
list.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list.toArray(new String[list.size()]);
}
public void cat(){ //显示
String[] st=readFile();
int i=0;
for (String string : st) {
if(lineNumber)
System.out.println(++i+":\t"+string);
}
try {
close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close() throws Exception{ //关闭流
read.close();
}
public static void main(String[] args) {
try {
MyReader myReader=new MyReader(new FileReader("/home/cys/Triangle.java"),true);
// myReader.setLineNumbr(true);
myReader.cat();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
作者:
eayonh
时间:
2015-7-18 02:14
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2