黑马程序员_java入门_IO流_3(字符流缓冲区)

来源:互联网 发布:淘宝购买记录查询器 编辑:程序博客网 时间:2024/05/21 09:15

------- android培训、java培训、期待与您交流! ----------

 

一字符流缓冲

BufferedWriter

BufferedReader

 

构建步骤;(写入缓冲区)

1.开流,开缓冲区

FileWriter fw=null;

BufferedWriter bufw=null;

2.找流的实例对象,将实例对象传入缓冲区

fw=new FileWriter("buf.txt");

bufw=new BufferedWriter(fw);

3.再用缓冲区再写

bufw.write("123");

4.写完后换行

bufw.newLine();

5.最后刷新

bufw.flush();

6.关闭缓冲区

bufw.close()

//其实关闭缓冲区也就是关闭流了

 

读入缓冲区的构建步骤

1.开流,开缓冲区

FileReader fr=null;

BufferedReader bufr=null;

2.建立流的实例对象,传流进去缓冲区

fr=new FileReader("buf.txt");

bufr=new BufferedReader(fr);

3.开始用缓冲区来读

String line=bufr.readLine()

4.关闭缓冲区

bufr.close();

 

二.自定义ReadLine()方法

private FileReader r;MyBufferedReader(FileReader r){this.r=r;}public String myReadLine() throws IOException{StringBuilder sb=new StringBuilder()int ch=0;while((ch=r.read())!=-1){if(ch=='\r')continue;if(ch=='\n')return sd.toString();elsesb.append((char)ch);}return null;}


三.装饰设计模式

将已有的对象,传入到另外一个类,可以加强方法

举例

class Person

{

  public void eat(){

 sop("吃饭

}

class SuperPerson

{

  private Person p;

 SuperPerson(Person p)

{

  this.p=p;

}

public void show(){

   p.eat()

 sop("12300");

}

class Test

{

    public static void main(String[] args)

{

     Person p=new Person()

   p.eat();

    SuperPerson su=new SuperPerson(p)

su.show();

 

 

}

 

}

 

 

}

}

四.装饰类和继承的关系

装饰类要比继承灵活,避免了继承体系的臃肿,降低了关联性在,增强了已有的对象

 

五.获取文件的大小

FileInputStream fis=new FileInputStream("fos.txt");  

byte[] buf=newbyte[fis.available()];//定义一个刚刚好的缓冲区,获取一个文件的大小了

 

六.读图片和MP3的实例

读图片class CopyPic{public static void main(String[] args){FileOutputStream fos=null;FileInputStream fis=null;try{fos=new FileOutputStream("");fis=new FileInputStream("");byte[] buf=new byte[1024];int len=0;while((len=fis.read(buf))!=-1){fos.writer(buf,0,len)}}catch(IOException e){throw new RuntimeExecption("");}finally{try{if(fis!==null)fis.close();}catch(IOException e){}try{if(fos!==null)f0s.close();}catch(IOException e){}}}///////////////////////////////////////////////////////////////import java.io.*class CopyMp3{public static void main(String[] args){long start=System.currenTimeMills();copy_1();long end=System.currenTimeMills();sop(end-start);}public static void copy_1() throw IOException;{BufferedInputStream bufis =new BufferedInputStream("");BufferedOutputStream bufos =new BufferedOutputStream("");int by=0;while((by=bufis.read())!=-1){bufos.write(by);}bufis.close();bufos.close();}}


 

 

 

 

原创粉丝点击