-------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.in
bis = 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;
}
//每次读取后指针归0
pos = 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位)