字符流
前面我们介绍了字节流,今天来看一下字符流,字节流可以对所有的文件进行读取,但是当文件中有中文字符时,我们如何对这些中文字符进行操作呢
我们先来看两种读文件的方法
public static void read() throws IOException{ FileReader fr=new FileReader("e:\java\java.txt"); int len=0; while((len=fr.read())!=-1){ System.out.println((char)len); } } public static void read2() throws IOException{ FileReader fr=new FileReader("e:\java\java.txt"); int len=0; char[] ch=new char[1024]; while((len=fr.read(ch))!=-1){ System.out.println(new String(ch,0,len)); } }
一般情况下,第二种方法效率高一点
再来看看用字符流往文件里写东西的方法
public static void writer() throws IOException{ FileWriter fw=new FileWriter("e:\java\java.txt",true); fw.write(100); fw.flush();//刷新,调用write方法后,要刷新才能把字符刷你去 fw.write("你好"); fw.flush(); char[]ch={'i','l','o','v','e'}; fw.write(ch); fw.close();//具有刷新一次的功能 }
其中flush是刷新,每次写之前都要刷新操作,然后在关闭
缓冲流
前面说的字节流和字符流都是效率比较低的流,下面说一个效率高一点的流,缓冲流
public static void read() throws IOException{ FileInputStream fos=new FileInputStream("e:\java\demo.txt"); BufferedInputStream bos=new BufferedInputStream(fos); int len=0; byte[]b=new byte[1024]; while((len=bos.read(b))!=-1){ System.out.println(new String(b,0,len)); } bos.close(); }
这是用缓冲流读文件的方法
我们可以计算一下程序运行的时间,不难看出这是最快的一种方法