自定义字符缓存流
import java.io.*;class mybuffered{ private FileReader fr = null; mybuffered(FileReader fr) { this.fr = fr ; } public String mynewline()throws IOException { StringBuilder sb = new StringBuilder(); int demo = 0; while ((demo = fr.read())!=-1) //多次返回之后指针还是会自动改变的 { if (demo == '\r') //int 和 char 之间是会自动匹配的 continue; if (demo == '\n') return sb.toString(); sb.append((char)demo); } if (sb.length()!=0) { return sb.toString(); } return null ; } public void myclose()throws IOException { fr.close(); }}public class anli{ public static void main (String[] args)throws IOException { FileReader fr = new FileReader("demo.txt"); mybuffered mf = new mybuffered(fr); String str = null; while ((str = mf.mynewline())!=null) { sop(str); } mf.myclose(); } public static void sop (Object obj) { System.out.println(obj); }}自定义字节缓存流
import java.io.*;class mybufferedinputstream{ private FileInputStream in ; private int pos = 0,count = 0; //在java中,类中可以初始化,这点和C++不一样 private byte[] bt = new byte[1024]; mybufferedinputstream(FileInputStream in) { this.in = in ; } public void myclose()throws IOException //只需要在这里抛出异常就可以了 { //这里用的是public,因为是公共部分给人调用的。。。 in.close(); //类中不可以调用自己类中的函数,除非是定义为静态的,就好像是主函数那样子 } public int myread ()throws IOException //返回值是byte,而返回类型确实int,其中的含义 { if (count==0) { count = in.read(bt); if (count < 0) { return -1; } pos = 0; //记得把pos恢复为0 byte term = bt[pos]; count--; pos++; return term&255; //255的含义 } else if (count > 0) { byte term = bt[pos]; //存放的是字节 count--; pos++; return term&255; } return -1; }}public class anli{ public static void main (String[] args)throws IOException { FileInputStream fi = new FileInputStream ("anli.java"); mybufferedinputstream ms = new mybufferedinputstream(fi); int term = 0; while ((term = ms.myread())!=-1) { sop((char)term); } } public static void sop(Object obj) { System.out.print(obj); }}