自己實現BufferedInputStream

來源:互聯網
上載者:User

package test;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;class MyBufferedInputStream{private InputStream in;private byte buf [] = new byte[1000];private int pos = 0;private int count = 0;MyBufferedInputStream(InputStream in){this.in = in;}public int myRead()throws IOException{if(count == 0){count = in.read(buf);if(count < 0)return -1;pos = 0;byte b = buf[pos];count--;pos++;return b & 0xff;}else if(count > 0){byte b = buf[pos];count--;pos++;return b & 0xff; /*由於b是byte類型,返回時Java會自動提升至int,所以為了確保不返回-1,將b與0xff與運算。 即讀取到b為-1時,2進位表示為11111111 byte——》int   11111111——》11111111 11111111 11111111 11111111 與0xff做與運算 ——》00000000 00000000 00000000 11111111 */}elsereturn -1;}public void myClose()throws IOException{in.close();}}public class MyBufferedInputStreamDemo{public static void main(String args[])throws IOException{long start = System.currentTimeMillis();copy();long end = System.currentTimeMillis();System.out.println((end - start) + "毫秒");}public static void copy()throws IOException{MyBufferedInputStream bufis = new MyBufferedInputStream(new FileInputStream("D:\\My Documents\\My Pictures\\未命名.jpg"));BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("D:\\My Documents\\My Pictures\\test.jpg"));int by = 0;while((by = bufis.myRead()) != -1){bufos.write(by);//byte強制轉換int 去掉之前做與運算產生的多與的3個8位。}bufos.close();bufis.myClose();}}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.