剛才在看幫助文檔的時候,發現Java io包中FilterReader和FilterWriter類沒使用過,所以想實踐一下。
還用以前的老方法,new一個出來,結果提示有錯誤:
Cannot instantiate the type FilterReader
不能實例化?
一查幫助文檔原來這樣寫道:
public abstract class FilterReader
extends Reader
Abstract class for reading filtered character streams
原來是抽象類啊,因為之前在面象對象這塊,沒怎麼用抽象類,都是紙上談兵(欠下的東西遲早要還的)。
嚇得我趕緊翻大神的博客來看:深入理解Java的接口和抽象類,最後搞定!
代碼如下:
1、先定義一個類FD,該類繼承抽象類FilterReader
public class FD extends FilterReader { public FD(BufferedReader br) { super(br); // TODO Auto-generated constructor stub } }
2、實例化FD
public void test() throws IOException { BufferedReader br = null; br = new BufferedReader(new InputStreamReader(new FileInputStream("E:/syl/1.html"), "UTF-8")); FD fd = new FD(br); int i = 0; char[] b = new char[1024]; int len = 0; while ((len = fd.read(b)) != -1) { System.out.println(b); } fd.close(); }
其中上面的第3行代碼等於:
FileInputStream in = new FileInputStream("E:/syl/1.html"); InputStreamReader inReader = new InputStreamReader(in, "UTF-8"); BufferedReader br = new BufferedReader(inReader);