記憶體流作用: 運行在記憶體中的流執行效率高,跟其他流不同的是,記憶體流是以記憶體為參照物,寫入記憶體使用量:ByteArrayOutputStream對象,讀取檔案使用ByteArrayInputStream對象使用如下: 使用如下:(關鍵代碼) ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { // 向記憶體中寫入內容 baos.write("呵呵呵呵".getBytes()); baos.flush(); // toByteArray() 將流中的內容 轉成byte數組 byte[] b= baos.toByteArray(); // 建立 記憶體輸入資料流 ByteArrayInputStream bais = new ByteArrayInputStream(b); byte[] b2 = new byte[50]; int count = bais.read(b2); System.out.println(new String(b2,0,count)); } 各個方法: ByteArrayOutputStream 註:writeTo(OutputStream out)方法內建自動重新整理功能寫入讀取檔案更加方便使用如下: FileInputStream fis = null; ByteArrayOutputStream baos = null; try { fis = new FileInputStream(new File("a.txt")); baos = new ByteArrayOutputStream(); byte[] bs = new byte[10]; int count = 0; while((count= fis.read(bs))!=-1){ // 寫到記憶體 baos.write(bs, 0, count); baos.flush(); } // 將記憶體中資料寫到本地檔案中 // writeTo 等同於 上個類中自己寫的 writeFile baos.writeTo(new FileOutputStream(new File("w.txt"))); } ByteArrayInputStream |