1 /* 2 * To change this license header, choose License Headers in Project Properties. 3 * To change this template file, choose Tools | Templates 4 * and open the template in the editor. 5 */ 6 package InputStream; 7 8 import java.io.BufferedInputStream; 9 import java.io.BufferedOutputStream; 10 import java.io.File; 11 import java.io.FileInputStream; 12 import java.io.FileOutputStream; 13 14 /** 15 * 16 * @author steven 17 */ 18 /* 19 IO 體系 20 字節流練習 21 InputStream 字節輸入流為抽象接口 ,不能直接創建對象,可以通過其子類 FileInputStream來創建對象 22 格式為: InputStream is = new FileInputStream("文件路徑"); 23 或者:FileInputStream fis = new FileInputSteam("文件路徑"); 24 如果想提高效率,可以使緩沖流來包裝,格式為: 25 BufferedInputStream bis = new BufferedInputStream(fis); 26 這種模式稱為裝修設計模式 27 OutputStream 字節輸出流,也為抽象接口,不能直接創建對象,可以通過其子類FileOutputStream來創建對象 28 格式為:OutputStream os = new FileOutputStream("文件路徑"); 29 或者 FileOutputStream fos = new FileOutStream("文件路徑"); 30 如果向提高效率,可以使用高效緩沖流包裝 31 格式為:BufferedOutputStream bos = new BufferedOutputStream(fos); 32 33 */ 34 public class InputStream_01 { 35 public static void main(String[] args) throws Exception { 36 File file = new File("c:\\test\\1.txt");//關聯文件 37 FileInputStream fis = new FileInputStream(file);//創建字節輸入流 38 BufferedInputStream bis = new BufferedInputStream(fis);//升級為高速緩沖輸入流 39 40 File copyfile = new File("c:\\copy.txt");//關聯新的復制文件 41 FileOutputStream fos = new FileOutputStream(copyfile);//創建字節寫出流 42 BufferedOutputStream bos = new BufferedOutputStream(fos);//升級為高速緩沖寫出流 43 44 byte[] buf = new byte[1024];//創建1kb的讀取緩沖數組; 45 int len ; 46 while((len = bis.read(buf)) != -1){//讀取內容記錄在buf數組中; 47 bos.write(buf, 0, len);//帶字符數組緩沖的高效寫出流,格式為buf.write(buf,0,len) 48 //其中buf為緩沖數組,BufferedOutputStream本身具有8Kb的緩沖大小 49 //每一將數組中1kb的數據加載到8Kb的緩沖區中,待到8kb緩沖區全部裝滿后 50 //系統會自動的將緩沖區的8kb內容一次性全部刷新到磁盤文件中; 51 //0為寫入的開始,len為寫入的長度,范圍為(0-len)包括0不包括len 52 bos.flush();//字節流不一定非要寫刷新,但是在結束虛擬機之前一定要關閉緩沖流的寫出, 53 bos.close();//否則寫出的文件不能被寫入到本地磁盤中,會被當做垃圾被虛擬機回收! 54 //System.out.print(new String(buf,0,len)); 55 } 56 } 57 58 59 60 61 }