標籤:style blog java color os 檔案
//自訂的緩衝區
import java.io.*;
class MyBufferedInputStream
{
private byte[] buf = new byte[1024];
private InputStream in;
private int pos = 0, count = 0;
MyBufferedInputStream(InputStream in){
this.in = in;
}
/*
一次讀一個位元組,從緩衝區位元組數組中讀。
*/
public int myRead(){
//通過in對象讀取硬碟資料,並儲存buf中
if(count == 0){
count = in.read(buf);
if(count < 0)
return -1;
pos = 0;
byte b = buf[pos];
count--;
pos++;
return b;
}else if(count > 0){
byte b = buf[pos];
count--;
pos++;
return b;
}
return -1;
}
public void myClose(){
in.close();
}
}
調用緩衝區:
import java.io.*;class CopyMp3 { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); copy_1(); long end = System.currentTimeMillis(); System.out.println(end- start); } //通過位元組流的緩衝區完成複製 public static void copy_2() throws Exception{ BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("c:\\1.mp3")); BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("c:\\2.mp3")); int by = 0; while((by = bufis.myRead()) != -1){ bufos.write(by); } bufos.close(); bufis.myClose(); }}
-----------------------
問題:
被複製的檔案出現0位元組
0000-0001
1111-1110
1111-1111
byte:-1 ---> int:-1
他會讓前面加1,為了讓前面補0,需要&255
最低四位&15
1 1 1 1
最低八位&255
1111 1111