IO字节流

输入流读取文件FileInputStream

//创建流对象
FileInputStream fis=new FileInputStream("1.txt");
//demo1(fis);
int b;
//从硬盘上读取一个字节
while((b=fis.read())!=-1) {
	System.out.println(b);
}
fis.close();

输出流读出文件FileOutputStream

//创建字节输出流对象,如果没有就创建一个,如果有的话,清空,然后再次写入。
FileOutputStream fos = new FileOutputStream("yy.txt");
//如果想续写的话,在第二个参数填true
//FileOutputStream fos = new FileOutputStream("yy.txt",true);
//虽然写的是一个int数,但是到文件上的是一个字节,会自动去除前三个8位。
fos.write(97);
fos.write(98);
fos.close();

通过一个字节一个字节的读取写入,copy文件

FileInputStream fis = new FileInputStream("11.jpg");
FileOutputStream fos = new FileOutputStream("22.jpg");
int b;
while((b=fis.read())!=-1) {
	fos.write(b);
}
fis.close();
fos.close();

通过多个字节的读取写入,copy文件,速度相对于单字节来说快很多。(小数组读取)

FileInputStream fis = new FileInputStream("1.txt");
FileOutputStream fos = new FileOutputStream("2.txt");
byte[] arr= new byte[2];
int len;
while((len=fis.read(arr))!=-1) {
	//从索引0开始到len结束
	fos.write(arr,0,len);
}
fis.close();
fos.close();

BufferedInputStream和BufferedOutputStream实现快速copy。(buffer读取)

FileInputStream fis = new FileInputStream("1.txt");
FileOutputStream fos = new FileOutputStream("5.txt");
//创建输入输出流缓冲区对象,对输入输出流进行包装,让其变得更加强大。
//内存的运算效率要比硬盘高得多,所以只要降低到硬盘的读写次数就会提高效率
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int b;
while((b=bis.read())!=-1) {
	bos.write(b);
}
bis.close();
bos.close();

用小数组的方式会更快一些,因为小数组的方式操作的是同一个数组,但是buffer的方式操作的是两个不同的数组。

三种copy方式,最快的是小数组类型,其次是buffer,最后是单字节。

//close方法具备刷新的功能,在关闭流之前就会刷新一次缓冲区,将缓冲区的字节全都刷新到文件上,再关闭。刷完之后不能再写。
//flush方法具备刷新的功能,刷完之后还可以继续写

IO的异常处理
1.6及以前的写法

FileInputStream fis=null;
		FileOutputStream fos=null;
		try {
			fis = new FileInputStream("1.txt");
			fos = new FileOutputStream("3.txt");
			int b;
			while ((b = fis.read()) != -1) {
				fos.write(b);
			} 
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			try {
				if(fis!=null) {
					fis.close();
				}
			} finally {
				if(fos!=null) {
					fos.close();
				}
			}
		}
	}

1.7及以后

//1.7以后的写法,try内部必须都是可以自动关闭的
		try(
			FileInputStream fis = new FileInputStream("1.txt");
			FileOutputStream fos = new FileOutputStream("5.txt");
			MyClose mc=	new MyClose();
		){
			int b;
			while((b=fis.read())!=-1) {
				fos.write(b);
			}
		}

	class MyClose implements AutoCloseable{
	public void close(){
		// TODO Auto-generated method stub
		System.out.println("wo");
	}
	
}

文件的加密和解密

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("22.jpg"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("33.jpg"));
int b;
while((b=bis.read())!=-1) {
	//将写出的字节异或上一个数,那么这个数就是秘钥,解密的时候再次异或就可以了
	bos.write(b ^ 123);
}
bis.close();
bos.close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值