- import java.io.*;
- class MyBufferedInputStreamDemo {
- public static void main(String[] args){
- copy();
-
- }
-
- public static void copy() {
- MyBufferedInputStream bin = null;
- BufferedOutputStream bout = null;
- try {
- bin = new MyBufferedInputStream(new FileInputStream("C:\\Users\\XK-21\\Desktop\\1.png"));
- bout = new BufferedOutputStream(new FileOutputStream("C:\\Users\\XK-21\\Desktop\\2.png"));
- int ch = 0;
- while((ch=bin.myRead()) != -1){
- bout.write(ch);
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- throw new RuntimeException("MP3复制失败");
- } finally{
- if(bin != null){
- try {
- bin.myClose();
- } catch (IOException e) {
- throw new RuntimeException("读取字节流关闭失败");
- }
- }
-
- if(bout != null){
- try {
- bout.close();
- } catch (IOException e) {
- throw new RuntimeException("写入字节流关闭失败");
- }
- }
- }
-
- }
- }
- class MyBufferedInputStream
- {
- private InputStream in;
- private byte[] buf = new byte[1024*4];
-
- private int pos = 0,count = 0;
-
- 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;
- pos = 0;
- byte b = buf[pos];
- count--;
- pos++;
- return b&255;
- }
- else if(count>0)
- {
- byte b = buf[pos];
- count--;
- pos++;
- return b&0xff;
- }
- return -1;
- }
- public void myClose()throws IOException
- {
- in.close();
- }
- }
复制代码
因为字节流在读一个字节的时候有可能会读到连续8个二进制1,对应的十进制是-1,这样的话数据还没读完就结束了,所以在写myRead()方法的时候把存到byte数组中的每个字节又与(&)上了255,而在写入调用write方法时会将int强转为byte,只取8位,这样取回的还是原来的数据。 但是,这是因为一读一写保证了数据没变,,,那假如我就是要用字节流来读取一个文本文件,然后打印在控制台上,那这样没有用到字节输出流的write方法那么打印的数据不就改变了吗? |
|