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 }