Java--IO流--字节流

文章目录

一、 字节流概述

二、 字节流读取文件

三、字节流写入文件

四、字节流写数据换行和追加

五、字节流写数据加异常处理

六、 字节流的缓冲区

七、字节缓冲流

八、文件的复制

一、字节流概述:

在计算机中,无论是文件、图片、音频还是视频 ,所有文件都是以二进制(字节)形式存在的。 针对文件的读写操作:JDK提供了两个类 FileInputStream和FileOutputStream

二、字节流读取文件

FileInputStream:由于从文件读取数据是重复的操作,因此需要通过循环语句来实现数据的持续操作,如果达到文件的末尾,返回-1。
	fos.read():读数据
	FileInputStream fos = new FileInputStream("D:\\wokspace1\\firstwork\\java.txt");
		int by;
		while((by=fos.read())!=-1)
		{
			System.out.print((char)by);
		}
	fos.close();

三、字节流写入文件

FileOutputStream:写入数据,自动创建一个新文件, 注意的是:如果这个文件已经存在,那么该文件的数据将被清空,再写入新数据。如果希望追加数据,使用构造函数()。
FileOutputStream fos = new FileOutputStream("D:\\wokspace1\\firstwork\\java.txt");
		fos.write(97);
		byte[] bys1= {97,98,99};
		byte[] bys2= "abcde".getBytes();
		fos.write(bys1);
		fos.write(bys2);
		fos.write(bys2,1,3);
		fos.close();

四、字节流写数据换行和追加

1.字节流写数据如何换行:

  • 写完数据后,加换行符
  • windows:\r\n
  • linux:\n
  • mac:\r

2.字节流写数据如何实现追加:

写入末尾而不是开头!
FileOutputStream fos = new FileOutputStream("D:\\wokspace1\\firstwork\\java.txt",true);
	

五、字节流写数据加异常处理

I/O流进行数据的读写会出现异常,一旦遇到异常,I/O的close()方法将无法执行,流对象所占用的系统资源将不能够释放,应该抛出。

在这里插入图片描述

	加入finally来释放资源
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream("D:\\wokspace1\\firstwork\\java.txt");
			fos.write("hello".getBytes());
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			if(fos!=null) {
				try {
					fos.close();
				}catch(IOException e) {
					e.printStackTrace();
				}
			}
		}

六、字节流的缓冲区

实现了文件的复制,但是一个字节一个字节的读写,需要频繁的操作文件,效率非常低。 定义一个字节数组作为缓冲区,就可以一次性读取多个字节的数据啦!

七、字节缓冲流

  • I/O包中提供了两个带缓冲的字节流
  • 应用程序是通过缓冲流来完成数据读写的,而缓冲流又是通过底层的字节流与设备进行关联的。
  • BufferedInputStream和BufferedOuputStream
    在这里插入图片描述

字节缓冲输出流:

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\wokspace1\\firstwork\\box.txt"));
		bos.write("hello\r\n".getBytes());
		bos.write("world\r\n".getBytes());
		bos.close();

字节缓冲输入流:

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\wokspace1\\firstwork\\box.txt"));
		byte[] bys = new byte[1024];
		int len=0;
		while((len=bis.read(bys))!=-1) {
			System.out.println(new String(bys,0,len));
		}

八、文件的复制

需要通过输入流来读取源文件中的数据,并通过输出流将数据写入新文件。

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\wokspace1\\firstwork\\bis.txt"));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\wokspace1\\firstwork\\bos.txt"));
		
		byte[] bys = new byte[1024];
		int len=0;
		while((len=bis.read(bys))!=-1) {
			bos.write(bys,0,len);
		}
		bos.close();
		bis.close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值