Java中IO流(4)——字节流(传智播客毕老师视频讲解)

基类:

OutputStream:写

InputStream:   读

1、FileOutputStream

import java.io.*;
public class OutputStreamDemo
{
	public static void main(String[] args) throws IOException
	{
		FileOutputStream f=new FileOutputStream("abc.txt");
		//将字符串变为字节数据,然后写入,
		//字节流中,写入的过程不需要刷新
		f.write("sadfasdf".getBytes()); 
		f.close();
	}
}
但在字符流中,每次写入都预先存入至内存的缓冲区中,因为在字符流操作中,字符流数据会把存入缓冲区中的数据与系统所带的编码表进行编码匹配,因此需要先存放于缓冲区,然后再刷新到目标文件中;但字节流不需要编码匹配,因此字节流的写入操作将直接把数据写入到目标文件中,而不需要刷新操作。
2、FileInputStream

方式一;

FileInputStream fr=new FileInputStream("abc.txt");
int b1;
while((b1=fr.read())!=-1)
	System.out.print((char)b1);
方式二;

byte[] b2=new byte[3];
int len;
while((len=fr.read(b2))!=-1)
	System.out.println(new String(b2,0,len));
方式三(字节流特有):
int num=fr.available();
byte[] b3=new byte[num];
fr.read(b3);
System.out.println(new String(b3));
方式三对比前两种方式,其优点是能直接读取目标文件的大小,以便分配好合适的内存资源;但其缺点就是如果所读取目标文件过大,则将分配很大的内存资源,导致内存不足,所以三种方式各有利弊!

2、练习:复制照片

import java.io.*;
public class photoCopy 
{	
	public static void main(String[] args)
	{
		FileOutputStream fw=null;
		FileInputStream fr=null;
		try
		{
			fw=new FileOutputStream("C:\\Users\\LJ_Z\\Desktop\\test.jpg");
			fr=new FileInputStream("C:\\Users\\LJ_Z\\Desktop\\1.jpg");
			
			//int len=fr.available();  //读方式三,用available()方法,直接分配刚刚好的内存空间
			//byte[] b=new byte[len];
			//fr.read(b);
			//fw.write(b);
			
			int len=0;                    
			byte[] b=new byte[1024];
			while((len=fr.read(b))!=-1)//读方式二,采用循环的方式,不断的将数据读出
				fw.write(b);
		}
		catch(Exception e)
		{
			throw new RuntimeException("照片拷贝失败");
		}
		finally
		{
			try
			{
				if(fw!=null)
					fw.close();
			}
			catch(IOException e)
			{
				System.out.println("关闭写流对象失败");
			}
			
			try
			{
				if(fr!=null)
					fr.close();
			}
			catch(IOException e)
			{
				System.out.println("关闭读流对象失败");
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值