loading黑马程序员之IO字节流(2-2)

来源:互联网 发布:淘宝刷流量会怎么样 编辑:程序博客网 时间:2024/05/21 19:21

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

字节流是最基本的流,文件的操作、网络数据的传输等等都依赖于字节流。

先来一个拷贝二进制文件的例子

package com.heima.io;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;/** * 对文件进行读写 */public class ReadAndWriteFileDemo {public static void main(String[] args) throws Exception {BufferedInputStream bis =null;BufferedOutputStream bos = null;try {//FileInputStream读硬盘进缓冲区//BufferedInputStream读缓冲区的数据//读取键盘:System.inbis = new BufferedInputStream(new FileInputStream(new File("1.avi")));bos = new BufferedOutputStream(new FileOutputStream(new File("3.avi")));byte[] buff = new byte[1024];int len = 0;while((len=bis.read(buff))!=-1){bos.write(buff, 0, len);}} catch (Exception e) {e.printStackTrace();}finally{try {bis.close();} catch (Exception e) {e.printStackTrace();}try {bos.close();} catch (Exception e) {e.printStackTrace();}}}}

然后,简单写一个模拟BufferedInputStream的read()方法的类,加深对BufferedInputStream封装流的理解

代码下面有图解,要好好理解。不理解的可以看黑马毕向东老师的Java视频。

package com.heima.io;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;/** * 功能:简单模拟BufferedInputStream的read()方法 */public class MyBufferedInputStreamDemo {public static void main(String[] args) {MyBufferedInputStream mbis =null;BufferedOutputStream bos = null;try {mbis = new MyBufferedInputStream(new FileInputStream(new File("1.avi")));bos = new BufferedOutputStream(new FileOutputStream(new File("2.avi")));int b;while((b= mbis.myRead())!=-1){bos.write(b);}} catch (Exception e) {e.printStackTrace();}finally{try {if(mbis!=null)mbis.myClose();} catch (Exception e) {e.printStackTrace();}try {if(bos!=null)bos.close();} catch (Exception e) {e.printStackTrace();}}}}class MyBufferedInputStream{private InputStream in ;private byte[] buf = new byte[1024];private int pos = 0, count=0;public MyBufferedInputStream(InputStream in){this.in = in;}//一次读一个字节,从缓冲区(字节数组)读取public int myRead() throws IOException{//通过in对象读取硬盘上的数据,并存储在buf中if(count==0){count = in.read(buf);//读if(count<0){return -1 & 255;}//每次读取后指针归0pos = 0;byte b = buf[pos];//存count--;//硬盘上剩余的字节数pos++;//指针return b  & 0xff;}else if(count>0){byte b = buf[pos];count--;pos++;return b;}return -1;}public void myClose() throws IOException{in.close();}}

Read() byte->int

Fos.write()只写最后一个字节(8)


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

0 0
原创粉丝点击