zoukankan      html  css  js  c++  java
  • IO 流 自定义字节流的缓冲区-read 和write 的特点

     1 package com.yyq;
     2 /*
     3  * 字节流的缓冲区
     4  * 为什么会造成这种问题呢?
     5  * 小原理:  第一个字节返回的是 -1??? 为什么会是 -1呢??
     6  * 11111110000110101000
     7  * 读一个字节 ,读取到了8个二进制位 1111-1111 -1  
     8  * byte 类型  的  -1 --------》int: -1
     9  * 11111111   -1 读到连续八个1 就会停下来
    10  * 补位的时候  它补的是  00000000 能保证不会停下来
    11  * 那么只要在前面补0 ,既可以保留原字节的数据不变,又可以避免-1的出现
    12  * 11111111 11111111 11111111 11111111
    13  * 00000000 00000000 00000000 11111111
    14  * ------------------------------------
    15  * 00000000 00000000 00000000 11111111 进行与操作
    16  * read 进行了强制转换,将最低8位保留下来了
    17  * write 方法在提升,4个字节
    18  * 这种机制保证了数据的原样性
    19  */
    20 import java.io.*;
    21 class MyBufferedInputStream{
    22     private InputStream in;
    23     
    24     private byte[] buf = new byte[1024];
    25     private int pos = 0;
    26     private int count = 0;
    27     MyBufferedInputStream(InputStream in){
    28         this.in = in;
    29     }
    30     // 自定义一个read 方法 
    31     //一次读一个字节,重缓冲区)(字节数组)获取
    32     public int myRead() throws IOException{
    33         // 通过in对象读取硬盘上的数据,并存储在buf中
    34         if(count == 0){
    35             
    36             count = in.read(buf);
    37             if(count<0){
    38                 return -1;
    39             }
    40             pos = 0;
    41             byte b = buf[pos];
    42             count--;
    43             pos++;
    44             return b&255;
    45         }
    46         else if(count>0){
    47             byte b = buf[pos];
    48             count--;
    49             pos++;
    50             return b&255;
    51         }
    52         return -1;
    53     }
    54     public void myClose() throws Exception{
    55         in.close();
    56     }
    57 }
    58 public class CopyMP3 {
    59     public static void main(String[] args) throws Exception {
    60         long start = System.currentTimeMillis();
    61         copy_1();
    62         long end = System.currentTimeMillis();
    63         System.out.println(end-start);
    64     }
    65     public static void copy_1() throws Exception{
    66         MyBufferedInputStream bufis = new MyBufferedInputStream(
    67                 new FileInputStream("1.jpg"));
    68         BufferedOutputStream bufos = new BufferedOutputStream(
    69                 new FileOutputStream("2.jpg"));
    70         byte[] buf = new byte[1024];
    71         int num = 0;
    72         while((num = bufis.myRead())!=-1){
    73             bufos.write(num);
    74         }
    75     }
    76 }
  • 相关阅读:
    【宗萨仁波切】研究佛教即是研究自己,而研究自己即是发现无我
    【佩玛.丘卓】在当下那一刻觉醒...
    佩玛·丘卓:人生基本的事实
    佩玛.丘卓的生活智慧——【空船】
    佩玛·丘卓 | 宽恕自己,重新开始
    佩玛·丘卓:修炼平等心
    佩玛•丘卓 :我们需要的皆已具足
    【佩玛丘卓】喂养好狼
    佩玛.丘卓:为事情如实的面目而喜悦
    佩玛·丘卓:精神勇士的口诀
  • 原文地址:https://www.cnblogs.com/yangyongqian/p/5153271.html
Copyright © 2011-2022 走看看