Java知识点:IO流中的字节流使用大全

字节流

全文先对各种流对象的使用进行示例说明,再对IO流对象的使用进行分类总结

一般使用方式

FileInputStream  fis = new  FileInputStream("d:\\a.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();  //关闭流对象
	

复制MP3文件例子:copy_1()

FileInputStream fis = new FileInputStream("d:\\0.mp3");
FileOutputStream fos = new FileOutputStream("d:\\1.mp3");
		
		byte[] buf = new byte[1024];
		
		int len = 0;
		while( (len=fis.read(buf)) != -1 ) {
			fos.write(buf,0,len);
			
		}
		fis.close();
		fos.close();

以上例子为自定义缓冲区的方式

copy_2()例子:BufferedInputStream

BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("d:\\0.mp3"));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("d:\\1.mp3"));
		
		byte[] buf = new byte[1024];
		
		int len = 0;
		while( (len=bufis.read(buf)) != -1 ) {
			bufos.write(buf,0,len);
			
		}
		bufis.close();
		bufos.close();

copy_3()例子

FileInputStream fis = new FileInputStream("d:\\0.mp3");
FileOutputStream fos = new FileOutputStream("d:\\1.mp3");

		
		byte[] buf = new byte[fis.available()];//建立一个刚刚好大小的数组
		
		fis.read(buf);
		fos.write(buf);
		
		fos.close();
		fis.close();

copy_4()例子:完全不用缓冲,读一个写一个(最慢的方式)

FileInputStream fis = new FileInputStream("d:\\0.mp3");
FileOutputStream fos = new FileOutputStream("d:\\1.mp3");

		int ch = 0;

		while(  (ch = fis.read())  !=   -1) {
			fos.write(ch);
			
		}
		fos.close();
		fis.close();

读取一个键盘录入的数据并打印

InputStream in = System.in;
		int ch = in.read();//阻塞式方法,没有输入的时候会一直等待
		System.out.println(ch);

上面这段代码后面不需要写in.close();写了以后,代码后面再出现System.in时会出现异常,这个是系统默认输入,不能关,关了以后,后面再也打不开了,除非重启整个系统。

读取键盘录入:方式2,变大写显示,如果是over,则结束录入

用户回车之前将录入的数据变成字符串即可,需要容器装,用StringBuilder
StringBuilder sb = new StringBuilder();                 //创建容器
InputStream in = System.in;                             //获取键盘读取流
		
		int ch = 0;                                     //定义变量记录读到的字节,并循环读取
		while((ch = in.read()) != -1) {
			if(ch == '\r')
				continue;
			else if(ch == '\n') {
				String temp = sb.toString();
				if("over".equals(temp))
					break;
				System.out.println(temp.toUpperCase());
				sb.delete(0, sb.length());
			}
			else {
				sb.append((char)ch);                    //存储之前判断是否是换行标记
				 
			}
			
		}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值