字節(jié)流Stream操作單元是字節(jié)款票,按流的方向分為字節(jié)輸入流InputStream和字節(jié)輸出流OutputStream。
是所有字節(jié)輸入流的父類迹辐,包含兩個(gè)核心方法:
intread()從流中一次讀取一個(gè)字節(jié)陌粹,返回類型雖然為四個(gè)字節(jié)的int型奏属,實(shí)際上只填充最后一個(gè)字節(jié),前三個(gè)都為0悼做。
intread(byte[] buffer)從流中連續(xù)讀取多個(gè)可用字節(jié)疯特,最不超過buffer.length中緩沖在buffer數(shù)組中,返回實(shí)際讀取字節(jié)數(shù)量肛走。
是所有字節(jié)輸出流的父類漓雅,包含兩個(gè)核心方法:
void write(intn)將參數(shù)最后一個(gè)字節(jié)輸出到流中。
void write(byte[] buffer,intoffset,intlength)將緩沖在buffer數(shù)組的字節(jié)信息從索引offset開始連接取length個(gè)輸出到流中。
本文以File作為輸入和輸出目標(biāo)和源介紹文件字節(jié)輸入流FileInputStream和FileOutputStream這兩個(gè)流類來復(fù)制d:\a.jpg至e:\a.jpg邻吞。组题。
示例代碼:
publicstaticvoidmain(String[]args) {
FileInputStreamfis=null;
FileOutputStreamfos=null;
try{
fis=newFileInputStream("d:\\a.jpg");
fos=newFileOutputStream("e:\\b.jpg");
intn=-1;
while((n=fis.read())!=-1){
fos.write(n);
}
}catch(FileNotFoundExceptione) {
e.printStackTrace();
}catch(IOExceptione) {
e.printStackTrace();
}finally{
try{
if(fos!=null){
fos.flush();
fos.close();
}
if(fis!=null)fis.close();
}catch(IOExceptione) {
e.printStackTrace();
}
}
}
}