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

------- 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();
		else
		sb.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=new byte[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();


	}

}


 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值