黑马程序员java基础之IO流中的字节流

本文详细介绍了Java中IO流的基本概念及应用,包括字节流的读写操作、图片复制、音乐文件复制等实例。同时讲解了如何使用缓冲区提高读写效率,以及如何处理键盘录入数据。

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

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

操作图片数据,就要用到字节流:InputStream(读),OutputStream(写)

1.用字节读写流读写一个文件

import java.io.*;
class FileStream
{
	public static void main(String[] args) throws IOException
	{
		writeFile();
		readFile_2();
	}

	public static void readFile() throws IOException
	{
		FileInputStream fis=new FileInputStream("fos.txt");
		int ch=0;
		while((ch=fis.read())!=-1)
		{
			System.out.println((char)ch);//一个字节一个字节的读
		}

		fis.close();
	}

	public static void readFile_1() 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));//将字节数组整组一起读出来
		}
		fis.close();
	}

	public static void readFile_2() throws IOException
	{
		FileInputStream fis=new FileInputStream("fos.txt");

		int num=fis.available();
		byte[] buf=new byte[num];//创建一个刚刚好的数组缓冲区
		System.out.println(num);

		fis.read(buf);//数组缓冲区刚好合适,就不用循环了
		System.out.println(new String(buf));

		fis.close();	
	}


	public static void writeFile() throws IOException
	{
		FileOutputStream fos=new FileOutputStream("fos.txt");
		fos.write("abcde".getBytes());
		fos.close();
	}
}

练习:复制一张图片

   步骤:用字节读取流对象和图片关联

    用字节写入流创建一个图片文件,用于存储获取到的图片数据

    通过循环读写,完成数据的存储

   关闭资源

import java.io.*;
class CopyPicture
{
	public static void main(String[] args)
	{
		FileOutputStream fos=null;
		FileInputStream fis=null;
		try
		{
			fos=new FileOutputStream("e:\\p2.jpg");
			fis=new FileInputStream("c:\\p1.jpg");

			byte[] buf=new byte[1024];
			int len=0;
			while((len=fis.read(buf))!=-1)
			{
				fos.write(buf,0,len);
			}
		}
		catch(IOException e)
		{
			throw  new RuntimeException("复制文件失败");
		}
		finally
		{
			try
			{
				if(fis!=null)
					fis.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}

			try
			{
				if(fos!=null)
					fos.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}
		}
	}
}

对于字节流的缓冲区,通过复制Mp3来演示

import java.io.*;
class CopyMusic
{
	public static void main(String[] args)throws IOException
	{
		long start=System.currentTimeMillis();//拷贝开始时间
		copy_1();
		long end=System.currentTimeMillis();//拷贝结束时间
		System.out.println(end-start);
	}
	
	public static void copy_1() throws IOException
	{
		FileInputStream fis=new FileInputStream("e:\\feng.mp3");
		FileOutputStream fos=new FileOutputStream("c:\\feng1.mp3");
		//建立字节缓冲区,并把流对象存入
		BufferedInputStream bufi=new BufferedInputStream(fis);
		BufferedOutputStream bufo=new BufferedOutputStream(fos);

		int by=0;
		while((by=bufi.read())!=-1)//当没有读取到字节流的末尾时
		{
			bufo.write(by);//写入字节缓冲区中
		}
		//关闭流资源
		bufi.close();
		bufo.close();
	}
}

自定义一个字节缓冲区
import java.io.*;
class MyBufferedInputStream
{
	private InputStream in;
	private byte[] buf=new byte[1024*4];
	private int pos=0,count=0;
	MyBufferedInputStream(InputStream in)
	{
	 	this.in=in;
	}

	//一次读一个字符,从缓冲区获取
	public int MyRead() throws IOException
	{
		
		if(count==0)
		{
			count=in.read(buf);//通过in对象读取硬盘上的数据,并存入buf中,用count计数读的个数
			if(count<0)
				return -1;
			pos=0;
			byte b=buf[pos];//取0角标元素,即第一个元素
			count--;
			pos++;
			return b&255;
	/*
	读到的头8个字节是111-11111,即为-1,如此在循环中就符合条件,会让虚拟机误以为是已经到了数据流的末尾,
	而返回值是int型就可以将字节提升,变成111-11111 111-11111 111-11111 111-11111,这样将-1前面的值补0
	即0000-0000 0000-0000 0000-0000 111-11111这样既可以提升字节,还可以避免与判断位的-1相同,可以继续循环
	而不会出现复制的音乐文件是0kb了,所以返回时,b&255就会将byte提升为int时,前面补0
	*/
		}
		else if(count>0)//取出剩下的元素
		{
			byte b=buf[pos];

			count--;
			pos++;
			return b&0xff;
		}
		return -1;	
	}
	public void myclose() throws IOException
	{
		in.close();
	}
}

读取键盘录入数据

import java.io.*;
class ReadIn
{
	public static void main(String[] args) throws IOException
	{
		InputStream in =System.in;//获取键盘录入对象
		StringBuilder sb=new StringBuilder(in);建立字符缓冲区
		while(true)
		{
			int ch=in.read();
			if(ch=='\r')
				continue;
			if(ch=='\n')
			{
				String s=sb.toString();
				if("over".equals(s))//如果输入的是“over”,则停止
					break;
				System.out.println(s.toUpperCase());
				sb.delete(0,sb.length()); //发现键盘不断输入的时候,字符串越来越长,
							//所以需要执行该动作在完成一次打印后就清空缓冲区
			}
			else
				sb.append((char)ch);	
		}


		in.close();
	}
}

转换流:InputStreamReader 将字节流对象转换成字符流,OutputStreamWriter将字符流对象转换成字节流

  注意:当涉及到字符编码转换时需要用到转换流,操作的文件字节输出流:FileOutputStream

import java.io.*;
class TransStreamDemo
{
	public static void main(String[] args)throws IOException
	{
		InputStream in=System.in;//获取键盘录入对象
		
		InputStreamReader isr=new InputStreamReader(in);//用转换流InputStreamReader将字节流对象转换成字符流对象,
		
		BufferedReader bufr=new BufferedReader(isr);//为了提高效率,对字符串使用缓冲区技术,
		
		OutputStream out=System.out;//获取控制台输出对象
		OutputStreamWriter osw=new OutputStreamWriter(out);//使用转换流将字符流转换成字节流
		BufferedWriter bufw=new BufferedWriter(osw);	//使用缓冲区技术,提高效率

		//开始循环,输出字符流数据
		String line=null;
		while((line=bufr.readLine())!=null)
		{
			if("over".equals(line))
				break;

			bufw.write(line.toUpperCase());	
			bufw.newLine();//转行
			bufw.flush();//刷新
		}
		bufr.close();
	}
}


流操作的基本规律:通过三个明确来完成

明确源和目的

源:输入流,InputStream  Reader

目的:输出流,OutputStream   Writer

操作的数据是否为纯文本

是:字符流;否:字节流

当体系明确后,再明确要使用哪个具体的对象

通过设备来进行区分:源设备:内存,硬盘,键盘

目的设备:内存,硬盘,控制台

改变标准输入输出设备System.setIn(new FileInputStream("demo.java")); System.setout(new PrintStream("z.txt"))


异常处理日志的建立

import java.io.*;
import java.util.*;
import java.text.*;
class ExceptionInfo
{
	public static void main(String[] args)
	{
		try
		{
			int[] arr= new int[2];
			System.out.println(arr[3]);
		}
		catch(Exception e)
		{
			try
			{
				Date d=new Date();//创建时间对象
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//创建格式化时间的对象
				String s=sdf.format(d);将时间传入到格式对象中
				PrintStream ps=new PrintStream("exeception.log");
				ps.println(s);
				System.setOut(ps);  //重置目的对象,便于记录异常事件

			}
			catch(IOException e1)
			{
				throw new RuntimeException("日志文件创建失败");
			}
				e.printStackTrace(new PrintStream(System.out));//将异常记录到文件中

		}
	}	
}


系统信息的处理

import java.util.*;
import java.io.*;
class SystemInfo
{
	public static void main(String[] args) throws IOException
	{
		Properties prop=System.getProperties();//获取系统的属性信息

		//System.out.println(prop);
		prop.list(new PrintStream("sys.txt"));//在打印流中创建文本文档保存系统信息
	}
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值