黑马程序员:IO流之字节流

本文介绍Java中字节流的基本操作,包括使用FileInputStream和FileOutputStream进行文件读写的方法,并通过实例展示了如何利用缓冲流BufferedInputStream和BufferedOutputStream提高图片复制效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

---------------------- android培训java培训、期待与您交流! ----------------------
/*
IO流之字节流的两个基类:
InputStream OutputStream
字节流的缓冲区
BufferedInputStream BufferedOutputStream
*/
import java.io.*;
class IODemo1 
{
	public static void main(String[] args) throws IOException
	{
		//fileInput();
		//fileOutput();
		//计算copyPic()方法执行所用的时间
		long start = System.currentTimeMillis();
		copyPic();
		long end = System.currentTimeMillis();
		System.out.println((end-start)+"毫秒");
	}
	
	
	public static void fileInput()throws IOException
	{
		FileInputStream fis = new FileInputStream("fos.txt");
		//字节流读取演示
		byte[] buf = new byte[1024];
		int len = 0;
		while((len = fis.read(buf))!= -1)
		{
			System.out.println(new String(buf,0,len));
		}
		//字节流特有读取方式。定义一个刚刚好的缓冲区,所以不用循环了
		//但是数据太大时会发生内存溢出。建议定义1024的整数倍。循环读取。
		byte[] buf1 = new byte[fis.available()];
		fis.read(buf1);
		System.out.println(new String(buf1));
		fis.close();
	}
	
	//字节流输出演示
	public static void fileOutput()throws IOException
	{
		FileOutputStream fos = new FileOutputStream("fos.txt");
		
		
		fos.write("djfasfs".getBytes());
		
		fos.close();
	}

	//字节流的缓冲区BufferedInputStream BufferedOutputStream
	public static void copyPic()
	{
		BufferedInputStream bufin = null;
		BufferedOutputStream bufout = null;
		try
		{
			bufin = new BufferedInputStream(new FileInputStream("1.jpg"));
			bufout = new BufferedOutputStream(new FileOutputStream("copy1.jpg"));
			int by = 0;
			while((by = bufin.read())!=-1)
			{
				bufout.write(by); 
			}

		}
		catch (IOException e)
		{
			throw new RuntimeException("复制失败");
		}
		finally
		{
			try
			{
				if(bufin != null)
					bufin.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException("读取流关闭失败");
			}
			try
			{
				if(bufout != null)
					bufout.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException("输出流关闭失败");
			}
		}
	}
}

---------------------- android培训java培训、期待与您交流! ----------------------详细请查看: http://edu.csdn.net/heima
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值